package cn.zyq.ykb.service.task.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.NumberUtil;
import cn.zyq.ykb.beans.config.*;
import cn.zyq.ykb.beans.pay.PayOrder;
import cn.zyq.ykb.beans.sys.SysAdmin;
import cn.zyq.ykb.beans.task.*;
import cn.zyq.ykb.beans.task.bo.*;
import cn.zyq.ykb.beans.task.dto.ClaimTaskDto;
import cn.zyq.ykb.beans.task.vo.*;
import cn.zyq.ykb.beans.user.User;
import cn.zyq.ykb.beans.user.UserBalance;
import cn.zyq.ykb.beans.user.UserPromotion;
import cn.zyq.ykb.beans.user.vo.GetUserVo;
import cn.zyq.ykb.mapper.config.ConfigBrokerageMapper;
import cn.zyq.ykb.mapper.config.ConfigRecordMapper;
import cn.zyq.ykb.mapper.config.ConfigTaskTypeMapper;
import cn.zyq.ykb.mapper.pay.PayOrderMapper;
import cn.zyq.ykb.mapper.sys.SysAdminMapper;
import cn.zyq.ykb.mapper.task.*;
import cn.zyq.ykb.mapper.user.UserBalanceMapper;
import cn.zyq.ykb.mapper.user.UserMapper;
import cn.zyq.ykb.mapper.user.UserPromotionMapper;
import cn.zyq.ykb.service.msg.MsgService;
import cn.zyq.ykb.service.pay.PayOrderService;
import cn.zyq.ykb.service.task.MyTaskAuditService;
import cn.zyq.ykb.service.task.MyTaskService;
import cn.zyq.ykb.service.task.TaskAuditService;
import cn.zyq.ykb.service.task.TaskService;
import cn.zyq.ykb.system.common.BaseService;
import cn.zyq.ykb.system.common.PageParam;
import cn.zyq.ykb.system.enums.core.*;
import cn.zyq.ykb.system.exception.BusinessException;
import cn.zyq.ykb.system.pay.config.PayProperties;
import cn.zyq.ykb.system.pay.core.enums.PayChannelEnum;
import cn.zyq.ykb.system.pay.core.enums.PayOrderStatusEnum;
import cn.zyq.ykb.system.ry.util.SecurityUtils;
import cn.zyq.ykb.system.task.delayQueue.DelayQueueManager;
import cn.zyq.ykb.system.task.delayQueue.DelayTask;
import cn.zyq.ykb.system.task.delayQueue.TaskBase;
import cn.zyq.ykb.system.utils.DateUtils;
import cn.zyq.ykb.system.utils.IPUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 任务Service业务层处理
 *
 * @author SystemAuth
 * @date 2023-05-22
 */
@Service
@Slf4j
public class TaskServiceImpl extends BaseService implements TaskService {
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private TaskStepMapper taskStepMapper;
    @Autowired
    private MyTaskMapper myTaskMapper;
    @Autowired
    private MyTaskAuditMapper taskAuditMapper;
    @Autowired
    private MyTaskAuditService taskAuditService;
    @Autowired
    private MyTaskService myTaskService;
    @Autowired
    private ConfigRecordMapper configRecordMapper;
    @Autowired
    private TaskAuditMapper auditMapper;
    @Autowired
    private TaskAuditService AuditService;
    @Autowired
    protected MsgService msgService;
    @Autowired
    private TaskPackageMapper taskPackageMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ConfigTaskTypeMapper configTaskTypeMapper;
    @Autowired
    private TaskPromptMapper taskPromptMapper;
    @Autowired
    private MyTaskAuditLogMapper myTaskAuditLogMapper;
    @Autowired
    private ConfigBrokerageMapper configBrokerageMapper;
    @Autowired
    private TaskOrderMapper taskOrderMapper;
    @Autowired
    private PayOrderService payOrderService;
    @Autowired
    private UserPromotionMapper userPromotionMapper;
    @Autowired
    private UserBalanceMapper userBalanceMapper;
    @Autowired
    private DelayQueueManager delayQueueManager;
    @Autowired
    private PayOrderMapper payOrderMapper;
    @Autowired
    PayProperties payProperties;
    @Autowired
    private SysAdminMapper sysAdminMapper;
    @Autowired
    private TaskPriceMapper taskPriceMapper;

    /**
     * 查询任务
     *
     * @param taskID    任务主键
     * @param type
     * @param loginUser
     * @return 任务
     */
    @Override
    public Task selectTaskByTaskID(Integer taskID, Integer type, User loginUser) {
        Task task = taskMapper.selectByPrimaryKey(taskID);
        int number = task.getPageView();
        ++number;
        log.info("数量：{}", number);
        task.setPageView(number);
        this.taskMapper.updateByPrimaryKeySelective(task);
        ConfigTaskType configTaskType = this.configTaskTypeMapper.selectByPrimaryKey(task.getConfigTaskTypeID());
        task.setConfigTaskType(configTaskType);
        User user = this.userMapper.selectByPrimaryKey(loginUser.getUserID());
        this.checkPriceByUser(task, user);
        TaskPrompt taskPrompt = new TaskPrompt();
        taskPrompt.setTaskID(taskID);
        List<TaskPrompt> select2 = this.taskPromptMapper.select(taskPrompt);
        task.setTaskPrompts(select2);
        List<TaskStep> select = this.taskStepMapper.selectByTaskID(taskID);
        task.setTaskStepList(select);
        if (type.equals(1)) {
            MyTask select1 = this.myTaskMapper.selectMyTask(taskID, loginUser.getUserID());
            if (BeanUtil.isEmpty(select1)) {
                MyTask myTask = new MyTask();
                myTask.setState(0);
                task.setMyTasks(myTask);
            } else {
                task.setMyTasks(select1);
                MyTaskAudit myTaskAudit = new MyTaskAudit();
//                myTaskAudit.setTaskID(taskID);
                myTaskAudit.setMyTaskID(select1.getMyTaskID());
                myTaskAudit.setUserID(loginUser.getUserID());
//                myTaskAudit.setStatus(1);
                MyTaskAudit myTaskAudit1 = this.taskAuditMapper.selectOne(myTaskAudit);
                task.setMyTaskAudit(myTaskAudit1);
            }

        }
        return task;
    }

    /**
     * 查询任务
     *
     * @param serviceID 业务ID
     * @return 任务
     */
    @Override
    public Task selectTaskByServiceID(String serviceID) {
        Task param = new Task();
        param.setDeleted(0);
        param.setServiceID(serviceID);
        return this.taskMapper.selectOne(param);
    }

    /**
     * 查询任务列表
     *
     * @param pageParam
     * @return 任务
     */
    @Override
    public List<Task> daoChu(PageParam pageParam) {
//        if (param.getState().equals(1)){
//            param.setState();
//        }
        log.info("入参：{}", pageParam);
        pageParam.getKv().put("deleted", 0);
        return this.taskMapper.list1(pageParam.getKv());
    }

    /**
     * 查询任务列表
     *
     * @param pageParam
     * @return 任务
     */
    @Override
    public PageInfo<Task> selectTaskList(PageParam pageParam, User loginUser) {
        PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
        log.info("分页页数：{}",pageParam.getPage());
        pageParam.getKv().put("deleted", 0);
        Integer orderField = (Integer) pageParam.getKv().get("sort");
        if (orderField.equals(SortEnum.ZX.getValue())) {
            pageParam.getKv().put("orderField", "submitTime");
            pageParam.getKv().put("orderType", "desc");
        } else if (orderField.equals(SortEnum.ZR.getValue())) {
            pageParam.getKv().put("orderField", "residueNumber");
            pageParam.getKv().put("orderType", "asc");
        } else if (orderField.equals(SortEnum.GYJ.getValue())) {
            pageParam.getKv().put("orderField", "price");
            pageParam.getKv().put("orderType", "desc");
        } else if (orderField.equals(SortEnum.YSS.getValue())) {
            pageParam.getKv().put("orderField", "expectTime");
            pageParam.getKv().put("orderType", "asc");
        } else {
            pageParam.getKv().put("orderField", "updateTime");
            pageParam.getKv().put("orderType", "desc");
        }
        List<Task> list = this.taskMapper.list(pageParam.getKv());
        for (Task task : list) {
            if (task.getSxExpireTime() != null) {
                if (LocalDateTime.now().compareTo(task.getSxExpireTime()) < 0) {
                    task.setSxProp(0L);
                }
            }
            if (task.getZdExpireTime() != null) {
                if (LocalDateTime.now().compareTo(task.getZdExpireTime()) < 0) {
                    task.setZdProp(0L);
                }
            }
            this.taskMapper.updateByPrimaryKeySelective(task);
            ConfigTaskType configTaskType = this.configTaskTypeMapper.selectByPrimaryKey(task.getConfigTaskTypeID());
            task.setConfigTaskType(configTaskType);
            User user = this.userMapper.selectByPrimaryKey(loginUser.getUserID());
            this.checkPriceByUser(task, user);
        }
        return new PageInfo<>(list);
    }

    /**
     * 检查用户任务可得价格
     *
     * @param task
     * @param user
     */
    public void checkPriceByUser(Task task, User user) {
        User user1 = this.userMapper.selectByPrimaryKey(user.getUserID());
        if (UserPositionEnum.FWS.getValue().equals(user.getPosition()) || UserPositionEnum.GR.getValue().equals(user.getPosition())) {
            return;
        }
        if (UserPositionEnum.ZS.getValue().equals(user.getPosition())) {
            task.setPriceType(1);
            task.setPrice(new BigDecimal(1));
        }
        TaskPrice taskPrice = new TaskPrice();
        if (user.getService() != 0){
            taskPrice = this.taskPriceMapper.selectByUser(user.getService(),task.getTaskID());
        }else {
            taskPrice = this.taskPriceMapper.selectByUser(user.getPerson(),task.getTaskID());
        }
        ConfigBrokerage configBrokerage = new ConfigBrokerage();
        if (user1.getPerson().equals(0)){
            configBrokerage = this.configBrokerageMapper.queryServiceProviderConfig(user1.getService());
        }else {
            configBrokerage = this.configBrokerageMapper.queryServiceProviderConfig(user1.getPerson());
        }
        if (UserPositionEnum.PT.getValue().equals(user1.getPosition())) {
            if (BeanUtil.isEmpty(taskPrice)){
                double div = NumberUtil.div(configBrokerage.getDefaultUserProportion().intValue(), 100, 2);
                if (div > 0){
                    BigDecimal mul = task.getPrice().multiply(new BigDecimal(div)).setScale(1,BigDecimal.ROUND_HALF_UP);
                    if (mul.compareTo(BigDecimal.ZERO) > 0) {
                        task.setPrice(mul);
                    }
                }
            }else {
                task.setPrice(taskPrice.getUserPrice());
            }
        } else if (UserPositionEnum.TDZ.getValue().equals(user1.getPosition())){
            if (BeanUtil.isEmpty(taskPrice)){
                double div = NumberUtil.div(configBrokerage.getDefaultCaptainProportion().intValue(), 100, 2);
                if (div > 0){
                    BigDecimal mul = task.getPrice().multiply(new BigDecimal(div)).setScale(1,BigDecimal.ROUND_HALF_UP);
                    if (mul.compareTo(BigDecimal.ZERO) > 0) {
                        task.setPrice(mul);
                    }
                }
            }else {
                task.setPrice(taskPrice.getTemPrice());
            }
        }

    }

    /**
     * 查询任务列表
     *
     * @param param
     * @return 任务
     */
    @Override
    public List<Task> selectTaskList(Task param) {
//        if (param.getState().equals(1)){
//            param.setState();
//        }
        log.info("入参：{}", param);
        param.setDeleted(0);
        return this.taskMapper.select(param);
    }

    /**
     * 新增任务
     *
     * @param bo 任务
     * @return 结果
     */
    @Override
    @Transactional
    public int insertTask(TaskAddBo bo, User loginUser) {
        log.info("任务新增请求参数：{}", bo);
        Task param = new Task();
        param.setDeleted(0);
        param.setProductName(bo.getProductName());
        List<Task> select = this.taskMapper.select(param);
        if (!CollectionUtils.isEmpty(select)){
            throw new BusinessException(ResponseCodeEnum.ERROR, "任务名重复，请修改后提交");
        }
        User user = this.userMapper.selectByPrimaryKey(loginUser.getUserID());
        if (!user.getPosition().equals(UserPositionEnum.FWS.getValue()) && !user.getPosition().equals(UserPositionEnum.GR.getValue())) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "只有服务商和个人用户才能发布新任务");
        }
        Task task = BeanUtil.copyProperties(bo, Task.class);
        task.setState(StateEnum.XS.getValue());
        task.setResidueNumber(task.getNumber());
        task.setTaskPackageID(0);
        task.setUserID(user.getUserID());
        task.setIsScreen(0);
        task.setPayMent(bo.getPrice().multiply(new BigDecimal(bo.getNumber())));
        task.setOrderType(TaskAuditTypeEnum.FB.getValue());
        task.setTaskState(TaskStateEnum.DSH.getValue());
        this.setCreateBaseData(task, user);
        int i = this.taskMapper.insertSelective(task);
        if (i == 0) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "新增任务失败");
        }
        List<TaskStep> taskSteps1 = new ArrayList<>();
        if (!CollectionUtils.isEmpty(bo.getTaskStepList())){
            //新增步骤表
            for (TaskAddBo.TaskSteps taskSteps : bo.getTaskStepList()) {
                TaskStep taskStep = new TaskStep();
                taskStep.setStepName(taskSteps.getStepName());
                taskStep.setExplain(taskSteps.getExplain());
                taskStep.setPicture(taskSteps.getPicture());
                taskStep.setTaskID(task.getTaskID());
                taskStep.setType(taskSteps.getType());
                this.setCreateBaseData(taskStep, user);
                taskSteps1.add(taskStep);
            }
            int i1 = this.taskStepMapper.insertList(taskSteps1);
            if (i1 == 0) {
                throw new BusinessException(ResponseCodeEnum.ERROR, "新增任务步骤失败");
            }
        }
        //新增任务审核表
        TaskAudit taskAudit = new TaskAudit();
        taskAudit.setUserID(user.getUserID());
        taskAudit.setTaskID(task.getTaskID());
        taskAudit.setAuditType(TaskAuditTypeEnum.FB.getValue());
        taskAudit.setAudit(TaskAuditEnum.SHZ.getValue());
        taskAudit.setPriceDifference(bo.getPrice().multiply(new BigDecimal(bo.getNumber())));
        this.setCreateBaseData(taskAudit, user);
        int i2 = this.auditMapper.insertSelective(taskAudit);
        if (i2 == 0) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "新增任务审核失败");
        }
        if (task.getEndTime() != null) {
            long l = DateUtils.durationToMillis(LocalDateTime.now(), task.getEndTime());
            //加入延时队列
            TaskBase base = new TaskBase(task.getServiceID(), 3, task.getServiceID());
            //获取相差时间
            DelayTask task1 = new DelayTask(base, l);
            this.delayQueueManager.put(task1);
            log.info("订单：{}加入延时队列,过期时间{}", task.getServiceID(), task.getEndTime());
        }
        return 1;
    }

    /**
     * 修改任务
     *
     * @param bo 任务
     * @return 结果
     */
    @Override
    public int updateTask(TaskUptBo bo, User loginUser) {
        Task task1 = this.taskMapper.selectByPrimaryKey(bo.getTaskID());
        if (BeanUtil.isEmpty(task1)) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "修改的任务不存在");
        }
        if (!task1.getTaskState().equals(TaskStateEnum.WCG.getValue()) &&
                !task1.getTaskState().equals(TaskStateEnum.YZT.getValue())) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "当前任务不是已暂停和未成功状态，不能修改该任务");
        }
        User user = this.userMapper.selectByPrimaryKey(loginUser.getUserID());
        Task task = BeanUtil.copyProperties(bo, Task.class);
        this.setUpdateBaseData(task, user);
        int i = this.taskMapper.updateByPrimaryKeySelective(task);
        if (i == 0) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "修改任务失败");
        }
        //修改步骤表数据
        TaskStep taskStep = new TaskStep();
        taskStep.setTaskID(task.getTaskID());
        List<TaskStep> select = this.taskStepMapper.select(taskStep);
        for (TaskStep step : select) {
            int i1 = this.taskStepMapper.deleteByPrimaryKey(step.getTaskStepID());
            if (i1 == 0) {
                throw new BusinessException(ResponseCodeEnum.ERROR, "修改步骤数据异常");
            }
        }
        //新增步骤表
        List<TaskStep> taskSteps2 = new ArrayList<>();
        for (TaskUptBo.TaskSteps taskSteps : bo.getTaskStepList()) {
            TaskStep taskStep1 = new TaskStep();
            taskStep1.setStepName(taskSteps.getStepName());
            taskStep1.setExplain(taskSteps.getExplain());
            taskStep1.setPicture(taskSteps.getPicture());
            taskStep1.setType(taskSteps.getType());
            taskStep1.setTaskID(task.getTaskID());
            this.setCreateBaseData(taskStep1, user);
            taskSteps2.add(taskStep1);
        }
        int i1 = this.taskStepMapper.insertList(taskSteps2);
        if (i1 == 0) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "新增任务步骤失败");
        }
        //增加操作记录表数据
        ConfigRecord configRecord = new ConfigRecord(
                loginUser.getUserID(),
                ConfigRecordTypeEnum.RW.getValue(),
                bo.getTaskID(),
                "对任务ID：" + bo.getTaskID() + "进行了修改"
        );
        this.setCreateBaseData(configRecord, loginUser);
        int i2 = this.configRecordMapper.insertSelective(configRecord);
        if (i2 == 0) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "新增操作记录表数据失败");
        }
        return 1;
    }

    /**
     * 批量删除任务
     *
     * @param taskIDs 需要删除的任务主键
     * @return 结果
     */
    @Override
    public int deleteTaskByTaskIDs(Integer[] taskIDs) {
        int i = 0;
        for (Integer taskID : taskIDs) {
            Task task = this.taskMapper.selectByPrimaryKey(taskID);
            if (BeanUtil.isEmpty(task)){
                throw new BusinessException("查不到该任务信息ID："+task.getTaskID());
            }
            Task updateInstance = this.getUpdateInstance(Task.class);
            updateInstance.setTaskID(task.getTaskID());
            updateInstance.setDeleted(1);
            i = this.taskMapper.updateByPrimaryKeySelective(updateInstance);
//            i += this.taskMapper.deleteByPrimaryKey(taskID);
        }
        return i;
    }

    /**
     * 删除任务信息
     *
     * @param taskID 任务主键
     * @return 结果
     */
    @Override
    public int deleteTaskByTaskID(Integer taskID) {
        Task task = this.taskMapper.selectByPrimaryKey(taskID);
        if (task == null) {
            return 0;
        } else {
            Task storeInfo = new Task();
            storeInfo.setTaskID(taskID);
            storeInfo.setDeleted(1);
            storeInfo.setUpdateBy(SecurityUtils.getSysAdminID());
            storeInfo.setUpdateTime(LocalDateTime.now());
            this.taskMapper.updateByPrimaryKeySelective(storeInfo);
            return 1;
        }
    }

    @Override
    public TaskVo selectTotal(Integer state, Integer taskPackageID, User loginUser) {
        User user = this.userMapper.selectByPrimaryKey(loginUser.getUserID());
        Task task = new Task();
        task.setState(state);
        task.setTaskPackageID(taskPackageID);
        task.setTaskState(1);
        task.setDeleted(0);
        List<Task> select = this.taskMapper.select(task);
        for (Task task1 : select) {
            this.checkPriceByUser(task1, user);
        }
        TaskVo taskVo = new TaskVo();
        int totalTime = select.stream().mapToInt(Task::getExpectTime).sum();
        BigDecimal totalPrice = select.stream().map(vo -> ObjectUtils.isEmpty(vo.getPrice()) ? new BigDecimal(0) : vo.getPrice())
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        long total = select.stream().count();
        taskVo.setTotal(total);
        taskVo.setTotalTime(totalTime);
        taskVo.setTotalPrice(totalPrice);
        return taskVo;
    }

    @Override
    @Transactional
    public MyTaskAudit claimTask(ClaimTaskDto dto, User loginUser) {
        log.info("领取任务传递的参数：{}", dto);
//        if (dto.getPicture().isEmpty()) {
//            throw new BusinessException(ResponseCodeEnum.NULL_VALUE, "审核图片必传");
//        }
//        if (dto.getInformation().isEmpty()) {
//            throw new BusinessException(ResponseCodeEnum.NULL_VALUE, "提交信息必传");
//        }
        MyTask myTask = this.myTaskMapper.selectByPrimaryKey(dto.getMyTaskID());
        if (BeanUtil.isEmpty(myTask)) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "该领取任务不存在");
        }
        Task task = this.taskMapper.selectByPrimaryKey(myTask.getTaskID());
        if (BeanUtil.isEmpty(task)) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "找不到该任务信息");
        }

        if (dto.getState().equals(1)) {
            if (dto.getType().equals(1)){
                MyTaskAudit myTaskAudit2 = new MyTaskAudit();
                myTaskAudit2.setTaskID(myTask.getTaskID());
                myTaskAudit2.setUserID(loginUser.getUserID());
                myTaskAudit2.setAudit(1);
                myTaskAudit2.setStatus(1);
                MyTaskAudit myTaskAudit1 = this.taskAuditMapper.selectOne(myTaskAudit2);
                if (BeanUtil.isNotEmpty(myTaskAudit1)) {
                    throw new BusinessException(ResponseCodeEnum.ERROR, "该任务已经提交审核，请勿重复提交");
                }
            }
            //扣减task剩余库存
            int i2 = task.getResidueNumber() - 1;
            task.setResidueNumber(i2);
            this.taskMapper.updateByPrimaryKeySelective(task);

            MyTaskAudit audit = new MyTaskAudit();
            audit.setTaskID(task.getTaskID());
            audit.setUserID(loginUser.getUserID());
            audit.setDeleted(0);
            audit.setMyTaskID(dto.getMyTaskID());
            MyTaskAudit audit1 = this.taskAuditMapper.selectOne(audit);
            if (BeanUtil.isNotEmpty(audit1)){
                throw new BusinessException(ResponseCodeEnum.ERROR, "该任务已经提交，请勿重复提交");
            }

            //新增我的领取任务审核表数据
            MyTaskAudit myTaskAudit = new MyTaskAudit();
            myTaskAudit.setTaskID(task.getTaskID());
            myTaskAudit.setUserID(loginUser.getUserID());
            List<String> information = dto.getInformation();
            myTaskAudit.setInformation(information.toString());
            List<String> picture = dto.getPicture();
            myTaskAudit.setAuditPicture(picture.toString());
            myTaskAudit.setAudit(1);
            myTaskAudit.setMyTaskID(dto.getMyTaskID());
            if (dto.getType().equals(1)){
                myTaskAudit.setStatus(1);
            }else {
                myTaskAudit.setStatus(2);
            }
            this.setCreateBaseData(myTaskAudit, loginUser);
            int i1 = this.taskAuditMapper.insertSelective(myTaskAudit);
            if (i1 == 0) {
                throw new BusinessException(ResponseCodeEnum.ERROR, "新增领取任务审核表失败");
            }
            //修改状态为待审核
            myTask.setState(2);
            this.myTaskMapper.updateByPrimaryKeySelective(myTask);

            //新增领取审核记录表
            MyTaskAuditLog myTaskAuditLog = new MyTaskAuditLog();
            myTaskAuditLog.setMyTaskID(myTask.getMyTaskID());
            myTaskAuditLog.setState(MyTaskAuditLogStateEnum.SHZ.getValue());
            this.setCreateBaseData(myTaskAuditLog, loginUser);
            int i3 = this.myTaskAuditLogMapper.insertSelective(myTaskAuditLog);
            if (i3 == 0) {
                throw new BusinessException(ResponseCodeEnum.ERROR, "新增审核记录表失败");
            }
            return myTaskAudit;
        } else {
            MyTask myTask1 = this.myTaskMapper.selectByPrimaryKey(dto.getMyTaskID());
            myTask1.setState(2);
            this.myTaskMapper.updateByPrimaryKeySelective(myTask1);
            //修改之前审核 重新提交
            MyTaskAudit myTaskAudit = this.taskAuditMapper.getAudit(myTask1.getMyTaskID(), myTask1.getUserID(), myTask1.getTaskID());
            List<String> information = dto.getInformation();
            myTaskAudit.setInformation(information.toString());
            List<String> picture = dto.getPicture();
            myTaskAudit.setAuditPicture(picture.toString());
            myTaskAudit.setAudit(1);
            this.setUpdateBaseData(myTaskAudit,loginUser);
            this.taskAuditMapper.updateByPrimaryKeySelective(myTaskAudit);
            return myTaskAudit;
        }
    }

    @Override
    public List<TaskPackage> taskPackage() {
//        List<TaskPackageVo> taskPackageVos = this.taskMapper.taskPackage();
//        for (TaskPackageVo taskPackageVo : taskPackageVos) {
//            TaskPackage taskPackage = taskPackageMapper.selectByPrimaryKey(taskPackageVo.getTaskPackageID());
//            if (taskPackage.getState().equals(1)) {
//                taskPackageVo.setPackageName(taskPackage.getPackageName());
//                taskPackageVo.setOnlineTime(taskPackage.getCreateTime());
//            }
//        }
        TaskPackage taskPackage = new TaskPackage();
        taskPackage.setDeleted(0);
        taskPackage.setState(1);
        List<TaskPackage> select = this.taskPackageMapper.select(taskPackage);
        for (TaskPackage aPackage : select) {
            TaskPackageVo taskPackageVos = this.taskMapper.taskPackage(aPackage.getTaskPackageID());
            aPackage.setTaskPackageVo(taskPackageVos);
        }
        return select;
    }

    @Override
    public PageInfo<Task> packageList(PageParam pageParam) {
        PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
        pageParam.getKv().put("deleted", 0);
        Integer orderField = (Integer) pageParam.getKv().get("sort");
        if (orderField.equals(SortEnum.ZX.getValue())) {
            pageParam.getKv().put("orderField", "submitTime");
            pageParam.getKv().put("orderType", "desc");
        } else if (orderField.equals(SortEnum.ZR.getValue())) {
            pageParam.getKv().put("orderField", "residueNumber");
            pageParam.getKv().put("orderType", "asc");
        } else if (orderField.equals(SortEnum.GYJ.getValue())) {
            pageParam.getKv().put("orderField", "price");
            pageParam.getKv().put("orderType", "desc");
        } else if (orderField.equals(SortEnum.YSS.getValue())) {
            pageParam.getKv().put("orderField", "expectTime");
            pageParam.getKv().put("orderType", "asc");
        } else {
            pageParam.getKv().put("orderField", "createTime");
            pageParam.getKv().put("orderType", "desc");
        }
        List<Task> list = this.taskMapper.packageList(pageParam.getKv());
        Integer taskPackageID = (Integer) pageParam.getKv().get("taskPackageID");
        list.forEach(p -> {
            TaskPackageVo taskPackage = this.taskMapper.getPackage(taskPackageID, (Integer) pageParam.getKv().get("state"));
            p.setTaskPackageVo(taskPackage);
            ConfigTaskType configTaskType = this.configTaskTypeMapper.selectByPrimaryKey(p.getConfigTaskTypeID());
            p.setConfigTaskType(configTaskType);
        });
        return new PageInfo<>(list);
    }

    @Override
    public PageInfo<Task> rewardList(PageParam pageParam) {
        PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
        pageParam.getKv().put("deleted", 0);
        List<Task> list = this.taskMapper.rewardList(pageParam.getKv());
        list.forEach(p -> {
//            TaskPackageVo taskPackage = this.taskMapper
//                    .getTaskPackage((Integer) pageParam.getKv().get("taskPackageID"));
//            if (BeanUtil.isNotEmpty(taskPackage)) {
//                TaskPackage taskPackage1 = taskPackageMapper.selectByPrimaryKey(taskPackage.getTaskPackageID());
//                if (!taskPackage1.getState().equals(0)) {
//                    taskPackage.setPackageName(taskPackage1.getPackageName());
//                    taskPackage.setOnlineTime(taskPackage1.getCreateTime());
//                }
//                p.setTaskPackageVo(taskPackage);
//            }
            TaskPackageVo taskPackage = this.taskMapper.getPackage((Integer) pageParam.getKv()
                    .get("taskPackageID"), (Integer) pageParam.getKv().get("state"));
            p.setTaskPackageVo(taskPackage);
            ConfigTaskType configTaskType = this.configTaskTypeMapper.selectByPrimaryKey(p.getConfigTaskTypeID());
            p.setConfigTaskType(configTaskType);
        });
        return new PageInfo<>(list);
    }

//    @Override
//    @Transactional
//    public void audit(TaskAuditBo param, SysAdmin loginAdmin) {
//        List<String> serviceIDs = param.getServiceIDs();
//        log.info("入参：{}",serviceIDs);
//        if (CollectionUtils.isEmpty(serviceIDs)){
//            throw new BusinessException("业务ID必传");
//        }
//        for (String serviceID : serviceIDs) {
//            MyTaskAudit taskAudit = this.taskAuditService.selectMyTaskAuditByServiceID(serviceID);
//            if (BeanUtil.isEmpty(taskAudit)) {
//                throw new BusinessException(ResponseCodeEnum.ERROR, "没有当前审核信息");
//            }
//            if (taskAudit.getAudit().equals(param.getAuditState())){
//                throw new BusinessException("该领取任务："+taskAudit.getMyTaskAuditID()+"已是该状态，批量删除失败");
//            }
//            //查询领取表的数据
//            MyTask myTask = this.myTaskMapper.selectByPrimaryKey(taskAudit.getMyTaskID());
//            if (BeanUtil.isEmpty(taskAudit)) {
//                throw new BusinessException(ResponseCodeEnum.ERROR, "没有当前领取信息");
//            }
//            taskAudit.setAuditorID(loginAdmin.getSysAdminID());
//            taskAudit.setAuditTime(LocalDateTime.now());
//            taskAudit.setAuditReason(param.getAuditReason());
//
//            //获取领取人信息
//            User user = this.userMapper.selectByPrimaryKey(myTask.getUserID());
//            if (BeanUtil.isEmpty(user)) {
//                throw new BusinessException(ResponseCodeEnum.ERROR, "领取人信息异常");
//            }
//
//            //获取当前领取的任务信息
//            Task task = this.taskMapper.selectByPrimaryKey(myTask.getTaskID());
//            if (BeanUtil.isEmpty(task)) {
//                throw new BusinessException(ResponseCodeEnum.ERROR, "找不到当前领取的任务信息");
//            }
//            BigDecimal oldPirce = task.getPrice();
//            //计算当前用户任务佣金
//            this.checkPriceByUser(task, user);
//            //发送消息
////        StringBuffer msg = new StringBuffer();
////        msg.append("你的领取审核");
//            //新增领取审核记录表
//            MyTaskAuditLog myTaskAuditLog = new MyTaskAuditLog();
//            myTaskAuditLog.setMyTaskID(myTask.getMyTaskID());
//            myTaskAuditLog.setRemark(param.getAuditReason());
//            if (param.getAuditState().equals(TaskAuditEnum.SHTG.getValue())) {
//                //查询任务原价
////            Task task1 = this.taskMapper.selectByPrimaryKey(myTask.getTaskID());
//                //获取当前用户的上级服务商
//                User user1 = this.userMapper.selectByPrimaryKey(user.getService());
//                //如果审核完成状态转为已完成，同时发放任务佣金，以及上级佣金
//                if (user.getPosition().equals(UserPositionEnum.FWS.getValue())) {
//                    //如果是服务商，增加自己的钱包，没有贡献收益
//                    user.setWallet(user.getWallet().add(task.getPrice()));
//                } else if (user.getPosition().equals(UserPositionEnum.TDZ.getValue())) {
//                    //如果是团队长，增加自己的钱包金额，同时返佣金给服务商
//                    user.setWallet(user.getWallet().add(task.getPrice()));
//                    //计算返佣金额
//                    BigDecimal price = oldPirce.subtract(task.getPrice());
//                    //新增上级团队长余额变动明细
//                    UserBalance userBalance = new UserBalance(
//                            user1.getUserID(),
//                            user1.getWallet().add(price),
//                            user1.getWallet(),
//                            price,
//                            taskAudit.getTaskID(),
//                            UserBalanceStatusEnum.HYZD.getValue(),
//                            user.getUserID(),
//                            "好友做单收益"
//                    );
//                    this.setCreateBaseData(userBalance, user);
//                    this.userBalanceMapper.insertSelective(userBalance);
//                    //增加服务商钱包余额
//                    user1.setWallet(user1.getWallet().add(price));
//                    //修改服务商钱包的余额
//                    this.userMapper.updateByPrimaryKeySelective(user1);
//
//                    //修改推广表数据
//                    UserPromotion promotion = new UserPromotion();
//                    promotion.setPUser(myTask.getUserID());
//                    promotion.setUserID(user.getService());
//                    promotion.setDeleted(0);
//                    UserPromotion userPromotion = this.userPromotionMapper.selectOne(promotion);
//                    userPromotion.setRealReturn(userPromotion.getRealReturn().add(task.getPrice()));
//                    userPromotion.setContribute(userPromotion.getContribute().add(price));
//                    userPromotion.setState(1);
//                    this.userPromotionMapper.updateByPrimaryKeySelective(userPromotion);
//
//                } else if (user.getPosition().equals(UserPositionEnum.PT.getValue())) {
//                    user.setWallet(user.getWallet().add(task.getPrice()));
//                    ConfigBrokerage configBrokerage = this.configBrokerageMapper.queryServiceProviderConfig(user.getService());
//                    //判断当前用户是否有上级团队长
//                    if (user.getTeamLeader() == 0) {
//                        //如果没有团队长 剩余的任务金额全给上级服务商
//                        //新增上级服务商余额变动明细
//                        UserBalance userBalance = new UserBalance(
//                                user1.getUserID(),
//                                user1.getWallet().add(oldPirce.subtract(task.getPrice())),
//                                user1.getWallet(),
//                                oldPirce.subtract(task.getPrice()),
//                                taskAudit.getTaskID(),
//                                UserBalanceStatusEnum.HYZD.getValue(),
//                                user.getUserID(),
//                                "好友做单收益"
//                        );
//                        this.setCreateBaseData(userBalance, user);
//                        this.userBalanceMapper.insertSelective(userBalance);
//                        user1.setWallet(user1.getWallet().add(oldPirce.subtract(task.getPrice())));
//                        //修改服务商钱包的余额
//                        this.userMapper.updateByPrimaryKeySelective(user1);
//
//                        //修改推广表数据
//                        UserPromotion promotion = new UserPromotion();
//                        promotion.setPUser(myTask.getUserID());
//                        promotion.setUserID(user.getInviteUserID());
//                        promotion.setDeleted(0);
//
//                        UserPromotion userPromotion = this.userPromotionMapper.selectOne(promotion);
//                        userPromotion.setRealReturn(userPromotion.getRealReturn().add(task.getPrice()));
//                        userPromotion.setContribute(userPromotion.getContribute().add(oldPirce.subtract(task.getPrice())));
//                        userPromotion.setState(1);
//                        this.userPromotionMapper.updateByPrimaryKeySelective(userPromotion);
//
//
//                    } else {
//                        //获取上级团队长用户信息
//                        User user2 = this.userMapper.selectByPrimaryKey(user.getTeamLeader());
//                        //计算团队长的佣金
//                        Integer captainProportion = configBrokerage.getDefaultCaptainProportion();
//                        double div = NumberUtil.div(captainProportion.intValue(), 100, 2);
//                        BigDecimal price = oldPirce.subtract(task.getPrice());
//                        Double mul = 0.0;
//                        if (div > 0) {
//                            mul = NumberUtil.mul(price.intValue(), div);
//                            if (mul > 1) {
//                                user2.setWallet(user2.getWallet().add(new BigDecimal(mul)));
//                            }
//                        }
//
//                        //获取上级团队长用户信息
//                        User user3 = this.userMapper.selectByPrimaryKey(user.getTeamLeader());
//                        //新增上级团队长余额变动明细
//                        UserBalance userBalance = new UserBalance(
//                                user3.getUserID(),
//                                user3.getWallet().add(new BigDecimal(mul)),
//                                user3.getWallet(),
//                                new BigDecimal(mul),
//                                taskAudit.getTaskID(),
//                                UserBalanceStatusEnum.HYZD.getValue(),
//                                user.getUserID(),
//                                "好友做单收益"
//                        );
//                        this.setCreateBaseData(userBalance, user);
//                        this.userBalanceMapper.insertSelective(userBalance);
//                        //修改推广表数据
//                        UserPromotion promotion = new UserPromotion();
//                        promotion.setPUser(myTask.getUserID());
//                        promotion.setUserID(user3.getUserID());
//                        promotion.setDeleted(0);
//                        UserPromotion userPromotion = this.userPromotionMapper.selectOne(promotion);
//                        if (BeanUtil.isNotEmpty(userPromotion)){
//                            userPromotion.setRealReturn(userPromotion.getRealReturn().add(task.getPrice()));
//                            userPromotion.setContribute(userPromotion.getContribute().add(new BigDecimal(mul)));
//                            userPromotion.setState(1);
//                            this.userPromotionMapper.updateByPrimaryKeySelective(userPromotion);
//                        }
//                        //获取服务商佣金
//                        BigDecimal fwsPrice = price.subtract(new BigDecimal(mul));
////                        user1.setWallet(user1.getWallet().add(fwsPrice));
//                        //新增服务商余额变动明细
//                        UserBalance userBalance1 = new UserBalance(
//                                user1.getUserID(),
//                                user1.getWallet().add(fwsPrice),
//                                user1.getWallet(),
//                                fwsPrice,
//                                taskAudit.getTaskID(),
//                                UserBalanceStatusEnum.HYZD.getValue(),
//                                user.getUserID(),
//                                "好友做单收益"
//                        );
//                        this.setCreateBaseData(userBalance1, user);
//                        this.userBalanceMapper.insertSelective(userBalance1);
//                        user1.setWallet(user1.getWallet().add(fwsPrice));
//                        //修改团队长的钱包余额
//                        this.userMapper.updateByPrimaryKeySelective(user2);
//                        //修改服务商钱包的余额
//                        this.userMapper.updateByPrimaryKeySelective(user1);
//
//                        //修改推广表数据
//                        UserPromotion pro = new UserPromotion();
//                        pro.setPUser(user.getTeamLeader());
//                        pro.setUserID(user1.getUserID());
//                        pro.setDeleted(0);
//                        UserPromotion userPromotion1 = this.userPromotionMapper.selectOne(pro);
//                        userPromotion1.setRealReturn(userPromotion1.getRealReturn().add(new BigDecimal(mul)));
//                        userPromotion1.setContribute(userPromotion1.getContribute().add(fwsPrice));
//                        userPromotion1.setState(1);
//                        this.userPromotionMapper.updateByPrimaryKeySelective(userPromotion1);
//
//                    }
//
//                } else {
//                    //钻石用户不统计余额,金额
//
//                    //新增上级服务商余额变动明细
//                    UserBalance userBalance1 = new UserBalance(
//                            user1.getUserID(),
//                            user1.getWallet().add(oldPirce),
//                            user1.getWallet(),
//                            oldPirce,
//                            taskAudit.getTaskID(),
//                            UserBalanceStatusEnum.HYZD.getValue(),
//                            user.getUserID(),
//                            "好友做单收益"
//                    );
//                    this.setCreateBaseData(userBalance1, user);
//                    this.userBalanceMapper.insertSelective(userBalance1);
//
//                    user1.setWallet(user1.getWallet().add(oldPirce));
//                    this.userMapper.updateByPrimaryKeySelective(user1);
//
//                    //修改推广表数据
//                    UserPromotion pro = new UserPromotion();
//                    pro.setPUser(myTask.getUserID());
//                    pro.setUserID(user1.getUserID());
//                    pro.setDeleted(0);
//                    UserPromotion userPromotion1 = this.userPromotionMapper.selectOne(pro);
//                    userPromotion1.setContribute(userPromotion1.getContribute().add(oldPirce));
//                    userPromotion1.setState(1);
//                    this.userPromotionMapper.updateByPrimaryKeySelective(userPromotion1);
//
//
//
//                }
//                //修改用户的钱包金额
//                this.userMapper.updateByPrimaryKeySelective(user);
//                //新增当前用户余额变动信息
//                UserBalance userBalance = new UserBalance(
//                        user.getUserID(),
//                        user.getWallet(),
//                        user.getWallet().subtract(task.getPrice()),
//                        task.getPrice(),
//                        taskAudit.getTaskID(),
//                        UserBalanceStatusEnum.ZZD.getValue(),
//                        user.getUserID(),
//                        "自做单收益"
//                );
//                this.setCreateBaseData(userBalance, user);
//                this.userBalanceMapper.insertSelective(userBalance);
//
//
//                taskAudit.setAudit(TaskAuditEnum.SHTG.getValue());
//                myTask.setState(MyTaskStateEnum.YWC.getValue());
//                myTaskAuditLog.setState(MyTaskAuditLogStateEnum.SHCG.getValue());
//
//
////            msg.append("审核通过");
//            } else if (param.getAuditState().equals(TaskAuditEnum.SHJJ.getValue())) {
//                taskAudit.setAudit(TaskAuditEnum.SHJJ.getValue());
//                myTask.setState(MyTaskStateEnum.WWC.getValue());
//                myTaskAuditLog.setState(MyTaskAuditLogStateEnum.SHJJ.getValue());
////            msg.append("审核未通过，原因：").append(param.getAuditReason());
//            } else if (param.getAuditState().equals(TaskAuditEnum.SHBH.getValue())) {
//                taskAudit.setAudit(TaskAuditEnum.SHBH.getValue());
//                myTask.setState(MyTaskStateEnum.BJ.getValue());
//                myTaskAuditLog.setState(MyTaskAuditLogStateEnum.SHBH.getValue());
////            msg.append("审核被驳回，原因：").append(param.getAuditReason());
//            } else {
//                throw new BusinessException(ResponseCodeEnum.ERROR, "审核类型错误");
//            }
//            this.taskAuditService.updateMyTaskAudit(taskAudit);
//            this.myTaskService.updateMyTask(myTask);
//
//            this.setCreateBaseData(myTaskAuditLog, loginAdmin);
//            int i2 = this.myTaskAuditLogMapper.insertSelective(myTaskAuditLog);
//            if (i2 == 0) {
//                throw new BusinessException(ResponseCodeEnum.ERROR, "新增审核记录表失败");
//            }
//        }
//
////        this.msgService.sendMsg(msg.toString(), param.getServiceID(), taskAudit.getUserID(), MsgTypeEnum.EXAMINE_MSG, loginAdmin);
//    }
    @Override
    @Transactional
    public void audit(TaskAuditBo param, SysAdmin loginAdmin) {
        List<String> serviceIDs = param.getServiceIDs();
        log.info("入参：{}",serviceIDs);
        if (CollectionUtils.isEmpty(serviceIDs)){
            throw new BusinessException("业务ID必传");
        }
        for (String serviceID : serviceIDs) {
            MyTaskAudit taskAudit = this.taskAuditService.selectMyTaskAuditByServiceID(serviceID);
            if (BeanUtil.isEmpty(taskAudit)) {
                throw new BusinessException(ResponseCodeEnum.ERROR, "没有当前审核信息");
            }
            if (taskAudit.getAudit().equals(param.getAuditState())){
                throw new BusinessException("该领取任务："+taskAudit.getMyTaskAuditID()+"已是该状态，批量删除失败");
            }
            //查询领取表的数据
            MyTask myTask = this.myTaskMapper.selectByPrimaryKey(taskAudit.getMyTaskID());
            if (BeanUtil.isEmpty(taskAudit)) {
                throw new BusinessException(ResponseCodeEnum.ERROR, "没有当前领取信息");
            }
            taskAudit.setAuditorID(loginAdmin.getSysAdminID());
            taskAudit.setAuditTime(LocalDateTime.now());
            taskAudit.setAuditReason(param.getAuditReason());

            //获取领取人信息
            User user = this.userMapper.selectByPrimaryKey(myTask.getUserID());
            if (BeanUtil.isEmpty(user)) {
                throw new BusinessException(ResponseCodeEnum.ERROR, "领取人信息异常");
            }
            //任务原价
            BigDecimal oldPirce = myTask.getPrice();
            //当前领取人实得单价
            BigDecimal actualPrice = myTask.getActualPrice();
            //新增领取审核记录表
            MyTaskAuditLog myTaskAuditLog = new MyTaskAuditLog();
            myTaskAuditLog.setMyTaskID(myTask.getMyTaskID());
            myTaskAuditLog.setRemark(param.getAuditReason());
            if (param.getAuditState().equals(TaskAuditEnum.SHTG.getValue())) {
                //获取当前用户的上级服务商
                User user1 = this.userMapper.selectByPrimaryKey(user.getService());
                //如果审核完成状态转为已完成，同时发放任务佣金，以及上级佣金
                if (user.getPosition().equals(UserPositionEnum.FWS.getValue()) || user.getPosition().equals(UserPositionEnum.GR.getValue())) {
                    //如果是服务商，增加自己的钱包，没有贡献收益
                    user.setWallet(user.getWallet().add(oldPirce));
                }else if (user.getPosition().equals(UserPositionEnum.TDZ.getValue())) {
                    //如果是团队长，增加自己的钱包金额，同时返佣金给服务商
                    user.setWallet(user.getWallet().add(actualPrice));
                    //计算返佣金额
                    BigDecimal price = oldPirce.subtract(actualPrice);
                    //新增上级服务商余额变动明细
                    UserBalance userBalance = new UserBalance(
                            user1.getUserID(),
                            user1.getWallet().add(price),
                            user1.getWallet(),
                            price,
                            taskAudit.getTaskID(),
                            UserBalanceStatusEnum.HYZD.getValue(),
                            user.getUserID(),
                            "好友做单收益"
                    );
                    this.setCreateBaseData(userBalance, user);
                    this.userBalanceMapper.insertSelective(userBalance);
                    //增加服务商钱包余额
                    user1.setWallet(user1.getWallet().add(price));
                    //修改服务商钱包的余额
                    this.userMapper.updateByPrimaryKeySelective(user1);

                    //修改推广表数据
                    UserPromotion promotion = new UserPromotion();
                    promotion.setPUser(myTask.getUserID());
//                    promotion.setUserID(user.getService());
                    promotion.setDeleted(0);
                    UserPromotion userPromotion = this.userPromotionMapper.selectOne(promotion);
                    userPromotion.setRealReturn(userPromotion.getRealReturn().add(actualPrice));
                    userPromotion.setContribute(userPromotion.getContribute().add(price));
                    userPromotion.setState(1);
                    this.userPromotionMapper.updateByPrimaryKeySelective(userPromotion);

                } else if (user.getPosition().equals(UserPositionEnum.PT.getValue())) {
                    user.setWallet(user.getWallet().add(actualPrice));
                    //判断是个人级别的用户还是服务商级别的用户
                    if (user.getPerson() != 0){
                        User grUser = this.userMapper.selectByPrimaryKey(user.getPerson());
                        if (BeanUtil.isEmpty(grUser)){
                            throw new BusinessException("当前用户的上级个人用户不存在");
                        }
                        //计算返佣金额
                        BigDecimal price = oldPirce.subtract(actualPrice);
                        //新增上级个人余额变动明细
                        UserBalance userBalance = new UserBalance(
                                grUser.getUserID(),
                                grUser.getWallet().add(price),
                                grUser.getWallet(),
                                price,
                                taskAudit.getTaskID(),
                                UserBalanceStatusEnum.HYZD.getValue(),
                                user.getUserID(),
                                "好友做单收益"
                        );
                        this.setCreateBaseData(userBalance, user);
                        this.userBalanceMapper.insertSelective(userBalance);
                        //修改上级个人用户钱包的余额
                        grUser.setWallet(grUser.getWallet().add(price));
                        this.userMapper.updateByPrimaryKeySelective(grUser);

                        //修改推广表数据
                        UserPromotion promotion = new UserPromotion();
                        promotion.setPUser(myTask.getUserID());
//                        promotion.setUserID(user.getInviteUserID());
                        promotion.setDeleted(0);

                        UserPromotion userPromotion = this.userPromotionMapper.selectOne(promotion);
                        userPromotion.setRealReturn(userPromotion.getRealReturn().add(actualPrice));
                        userPromotion.setContribute(userPromotion.getContribute().add(oldPirce.subtract(actualPrice)));
                        userPromotion.setState(1);
                        this.userPromotionMapper.updateByPrimaryKeySelective(userPromotion);

                    }else {
                        ConfigBrokerage configBrokerage = this.configBrokerageMapper.queryServiceProviderConfig(user.getService());
                        //判断当前用户是否有上级团队长
                        if (user.getTeamLeader() == 0) {
                            //如果没有团队长 剩余的任务金额全给上级服务商
                            //新增上级服务商余额变动明细
                            UserBalance userBalance = new UserBalance(
                                    user1.getUserID(),
                                    user1.getWallet().add(oldPirce.subtract(actualPrice)),
                                    user1.getWallet(),
                                    oldPirce.subtract(actualPrice),
                                    taskAudit.getTaskID(),
                                    UserBalanceStatusEnum.HYZD.getValue(),
                                    user.getUserID(),
                                    "好友做单收益"
                            );
                            this.setCreateBaseData(userBalance, user);
                            this.userBalanceMapper.insertSelective(userBalance);
                            user1.setWallet(user1.getWallet().add(oldPirce.subtract(actualPrice)));
                            //修改服务商钱包的余额
                            this.userMapper.updateByPrimaryKeySelective(user1);

                            //修改推广表数据
                            UserPromotion promotion = new UserPromotion();
                            promotion.setPUser(myTask.getUserID());
//                            promotion.setUserID(user.getInviteUserID());
                            promotion.setDeleted(0);

                            UserPromotion userPromotion = this.userPromotionMapper.selectOne(promotion);
                            userPromotion.setRealReturn(userPromotion.getRealReturn().add(actualPrice));
                            userPromotion.setContribute(userPromotion.getContribute().add(oldPirce.subtract(actualPrice)));
                            userPromotion.setState(1);
                            this.userPromotionMapper.updateByPrimaryKeySelective(userPromotion);
                        }else {
                            //获取上级团队长用户信息
                            User user2 = this.userMapper.selectByPrimaryKey(user.getTeamLeader());
                            //计算团队长的佣金
                            Integer captainProportion = configBrokerage.getDefaultCaptainProportion();
                            double div = NumberUtil.div(captainProportion.intValue(), 100, 2);
                            BigDecimal price = oldPirce.subtract(actualPrice);
                            BigDecimal mul = new BigDecimal(0);
                            if (div > 0) {
                                mul =price.multiply(new BigDecimal(div)).setScale(1,BigDecimal.ROUND_HALF_UP);
                                if (mul.compareTo(BigDecimal.ZERO) > 0) {
                                    user2.setWallet(user2.getWallet().add(mul));
                                }
                            }

                            //获取上级团队长用户信息
                            User user3 = this.userMapper.selectByPrimaryKey(user.getTeamLeader());
                            //新增上级团队长余额变动明细
                            UserBalance userBalance = new UserBalance(
                                    user3.getUserID(),
                                    user3.getWallet().add(mul),
                                    user3.getWallet(),
                                    mul,
                                    taskAudit.getTaskID(),
                                    UserBalanceStatusEnum.HYZD.getValue(),
                                    user.getUserID(),
                                    "好友做单收益"
                            );
                            this.setCreateBaseData(userBalance, user);
                            this.userBalanceMapper.insertSelective(userBalance);
                            //修改推广表数据
                            UserPromotion promotion = new UserPromotion();
                            promotion.setPUser(myTask.getUserID());
//                            promotion.setUserID(user3.getUserID());
                            promotion.setDeleted(0);
                            UserPromotion userPromotion = this.userPromotionMapper.selectOne(promotion);
                            if (BeanUtil.isNotEmpty(userPromotion)){
                                userPromotion.setRealReturn(userPromotion.getRealReturn().add(actualPrice));
                                userPromotion.setContribute(userPromotion.getContribute().add(mul));
                                userPromotion.setState(1);
                                this.userPromotionMapper.updateByPrimaryKeySelective(userPromotion);
                            }
                            //获取服务商佣金
                            BigDecimal fwsPrice = price.subtract(mul);
//                        user1.setWallet(user1.getWallet().add(fwsPrice));
                            //新增服务商余额变动明细
                            UserBalance userBalance1 = new UserBalance(
                                    user1.getUserID(),
                                    user1.getWallet().add(fwsPrice),
                                    user1.getWallet(),
                                    fwsPrice,
                                    taskAudit.getTaskID(),
                                    UserBalanceStatusEnum.HYZD.getValue(),
                                    user.getUserID(),
                                    "好友做单收益"
                            );
                            this.setCreateBaseData(userBalance1, user);
                            this.userBalanceMapper.insertSelective(userBalance1);
                            user1.setWallet(user1.getWallet().add(fwsPrice));
                            //修改团队长的钱包余额
                            this.userMapper.updateByPrimaryKeySelective(user2);
                            //修改服务商钱包的余额
                            this.userMapper.updateByPrimaryKeySelective(user1);

                            //修改推广表数据
                            UserPromotion pro = new UserPromotion();
                            pro.setPUser(user.getTeamLeader());
//                            pro.setUserID(user1.getUserID());
                            pro.setDeleted(0);
                            UserPromotion userPromotion1 = this.userPromotionMapper.selectOne(pro);
                            userPromotion1.setContribute(userPromotion1.getContribute().add(fwsPrice));
                            userPromotion1.setState(1);
                            this.userPromotionMapper.updateByPrimaryKeySelective(userPromotion1);

                        }
                    }

                }else {
                    //钻石用户不统计余额,金额
                    //新增上级服务商余额变动明细
                    UserBalance userBalance1 = new UserBalance(
                            user1.getUserID(),
                            user1.getWallet().add(oldPirce),
                            user1.getWallet(),
                            oldPirce,
                            taskAudit.getTaskID(),
                            UserBalanceStatusEnum.HYZD.getValue(),
                            user.getUserID(),
                            "好友做单收益"
                    );
                    this.setCreateBaseData(userBalance1, user);
                    this.userBalanceMapper.insertSelective(userBalance1);

                    user1.setWallet(user1.getWallet().add(oldPirce));
                    this.userMapper.updateByPrimaryKeySelective(user1);

                    //修改推广表数据
                    UserPromotion pro = new UserPromotion();
                    pro.setPUser(myTask.getUserID());
//                    pro.setUserID(user1.getUserID());
                    pro.setDeleted(0);
                    UserPromotion userPromotion1 = this.userPromotionMapper.selectOne(pro);
                    userPromotion1.setContribute(userPromotion1.getContribute().add(oldPirce));
                    userPromotion1.setState(1);
                    this.userPromotionMapper.updateByPrimaryKeySelective(userPromotion1);



                }
                //修改用户的钱包金额
                this.userMapper.updateByPrimaryKeySelective(user);
                //新增当前用户余额变动信息
                UserBalance userBalance = new UserBalance(
                        user.getUserID(),
                        user.getWallet(),
                        user.getWallet().subtract(actualPrice),
                        actualPrice,
                        taskAudit.getTaskID(),
                        UserBalanceStatusEnum.ZZD.getValue(),
                        user.getUserID(),
                        "自做单收益"
                );
                this.setCreateBaseData(userBalance, user);
                this.userBalanceMapper.insertSelective(userBalance);

                taskAudit.setAudit(TaskAuditEnum.SHTG.getValue());
                myTask.setState(MyTaskStateEnum.YWC.getValue());
                myTaskAuditLog.setState(MyTaskAuditLogStateEnum.SHCG.getValue());
            }
            else if (param.getAuditState().equals(TaskAuditEnum.SHJJ.getValue())) {
                taskAudit.setAudit(TaskAuditEnum.SHJJ.getValue());
                myTask.setState(MyTaskStateEnum.WWC.getValue());
                myTaskAuditLog.setState(MyTaskAuditLogStateEnum.SHJJ.getValue());

            } else if (param.getAuditState().equals(TaskAuditEnum.SHBH.getValue())) {
                taskAudit.setAudit(TaskAuditEnum.SHBH.getValue());
                myTask.setState(MyTaskStateEnum.BJ.getValue());
                myTaskAuditLog.setState(MyTaskAuditLogStateEnum.SHBH.getValue());
            } else {
                throw new BusinessException(ResponseCodeEnum.ERROR, "审核类型错误");
            }
            this.taskAuditService.updateMyTaskAudit(taskAudit);
            this.myTaskService.updateMyTask(myTask);

            this.setCreateBaseData(myTaskAuditLog, loginAdmin);
            int i2 = this.myTaskAuditLogMapper.insertSelective(myTaskAuditLog);
            if (i2 == 0) {
                throw new BusinessException(ResponseCodeEnum.ERROR, "新增审核记录表失败");
            }

        }
    }



    @Override
    public PageInfo<Task> publishing(PageParam pageParam, User loginUser) {
        PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
        pageParam.getKv().put("deleted", 0);
        pageParam.getKv().put("userID", loginUser.getUserID());
        List<Task> list = this.taskMapper.publishing(pageParam.getKv());
        list.forEach(p -> {
            Integer myTaskVo = this.myTaskMapper.selectByTaskIDDsh(p.getTaskID());
            Integer myTaskVo1 = this.myTaskMapper.selectByTaskIDYwc(p.getTaskID());
            p.setDshNumber(myTaskVo);
            p.setYwcNumber(myTaskVo1);
        });
        return new PageInfo<>(list);
    }

    @Override
    public int upTask(Task task, User loginUser) {
        Task task1 = this.selectTaskByServiceID(task.getServiceID());
        if (BeanUtil.isEmpty(task1)) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "该任务不存在，开始任务失败");
        }
        if (!task1.getTaskState().equals(TaskStateEnum.YZT.getValue())) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "该任务不是暂停状态，开始任务失败");
        }
        task1.setTaskState(TaskStateEnum.JXZ.getValue());
        this.setUpdateBaseData(task1, loginUser);
        int i = this.taskMapper.updateByPrimaryKeySelective(task1);
        if (i == 0) {
            log.info("修改状态失败");
            throw new BusinessException(ResponseCodeEnum.ERROR, "修改状态失败");
        }
        //增加记录表
        ConfigRecord configRecord = new ConfigRecord();
        configRecord.setUserID(loginUser.getUserID());
        configRecord.setTaskID(task1.getTaskID());
        configRecord.setType(ConfigRecordTypeEnum.KS.getValue());
        configRecord.setContent("开始任务");
        this.setCreateBaseData(configRecord, loginUser);
        int i1 = this.configRecordMapper.insertSelective(configRecord);
        if (i1 == 0) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "新增记录表异常");
        }
        return 1;
    }

    @Override
    public int downTask(Task task, User loginUser) {
        Task task1 = this.selectTaskByServiceID(task.getServiceID());
        if (BeanUtil.isEmpty(task1)) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "该任务不存在，暂停任务失败");
        }
        if (!task1.getTaskState().equals(TaskStateEnum.JXZ.getValue())) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "该任务不是进行中状态，暂停任务失败");
        }
        task1.setTaskState(TaskStateEnum.YZT.getValue());
        this.setUpdateBaseData(task1, loginUser);
        int i = this.taskMapper.updateByPrimaryKeySelective(task1);
        if (i == 0) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "修改状态失败");
        }
        //增加记录表
        ConfigRecord configRecord = new ConfigRecord();
        configRecord.setUserID(loginUser.getUserID());
        configRecord.setTaskID(task1.getTaskID());
        configRecord.setType(ConfigRecordTypeEnum.ZT.getValue());
        configRecord.setContent("暂停任务");
        this.setCreateBaseData(configRecord, loginUser);
        int i1 = this.configRecordMapper.insertSelective(configRecord);
        if (i1 == 0) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "新增记录表异常");
        }
        return 1;
    }

    @Override
    public Task getUptTask(Integer taskID, User loginUser) {
        Task task = this.taskMapper.selectByPrimaryKey(taskID);
        return task;
    }

    @Override
    @Transactional
    public void auditTask(TaskAuditBo param, SysAdmin loginAdmin) {
        TaskAudit taskAudit = this.AuditService.selectTaskAuditByServiceID(param.getServiceID());
        if (BeanUtil.isEmpty(taskAudit)) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "该任务审核信息不存在");
        }
        //查询任务表信息
        Task task = this.taskMapper.selectByPrimaryKey(taskAudit.getTaskID());
        if (BeanUtil.isEmpty(task)) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "该任务不存在");
        }
        taskAudit.setAuditorID(loginAdmin.getSysAdminID());
        taskAudit.setAuditTime(LocalDateTime.now());
        taskAudit.setAuditReason(param.getAuditReason());
        if (taskAudit.getAuditType().equals(TaskAuditTypeEnum.FB.getValue())) {
            if (param.getAuditState().equals(TaskAuditEnum.SHTG.getValue())) {
                taskAudit.setAudit(TaskAuditEnum.SHTG.getValue());
                task.setTaskState(TaskStateEnum.DZF.getValue());
                task.setPayMent(taskAudit.getPriceDifference());
            } else if (param.getAuditState().equals(TaskAuditEnum.SHJJ.getValue())) {
                taskAudit.setAudit(TaskAuditEnum.SHJJ.getValue());
                task.setTaskState(TaskStateEnum.WCG.getValue());
            } else if (param.getAuditState().equals(TaskAuditEnum.SHBH.getValue())) {
                taskAudit.setAudit(TaskAuditEnum.SHBH.getValue());
                task.setTaskState(TaskStateEnum.BJ.getValue());
            } else {
                throw new BusinessException(ResponseCodeEnum.ERROR, "审核类型错误");
            }
        } else if (taskAudit.getAuditType().equals(TaskAuditTypeEnum.XGJG.getValue()) ||
                taskAudit.getAuditType().equals(TaskAuditTypeEnum.XGSL.getValue())) {
            if (param.getAuditState().equals(TaskAuditEnum.SHTG.getValue())) {
                taskAudit.setAudit(TaskAuditEnum.SHTG.getValue());
                task.setTaskState(TaskStateEnum.DZF.getValue());
                task.setPayMent(taskAudit.getPriceDifference());
            } else if (param.getAuditState().equals(TaskAuditEnum.SHJJ.getValue())) {
                taskAudit.setAudit(TaskAuditEnum.SHJJ.getValue());
                task.setTaskState(taskAudit.getState());
                task.setPrice(taskAudit.getPrice());
                task.setPayMent(new BigDecimal(0));
            } else if (param.getAuditState().equals(TaskAuditEnum.SHBH.getValue())) {
                taskAudit.setAudit(TaskAuditEnum.SHBH.getValue());
                task.setTaskState(TaskStateEnum.BJ.getValue());
            } else {
                throw new BusinessException(ResponseCodeEnum.ERROR, "审核类型错误");
            }
        } else {

            if (param.getAuditState().equals(TaskAuditEnum.SHTG.getValue())) {
                taskAudit.setAudit(TaskAuditEnum.SHTG.getValue());
                //减少数量的直接状态修改为原始状态
                task.setTaskState(task.getUptState());
            } else if (param.getAuditState().equals(TaskAuditEnum.SHJJ.getValue())) {
                taskAudit.setAudit(TaskAuditEnum.SHJJ.getValue());
                task.setTaskState(taskAudit.getState());
                task.setPrice(taskAudit.getPrice());
                task.setPayMent(new BigDecimal(0));
            } else if (param.getAuditState().equals(TaskAuditEnum.SHBH.getValue())) {
                taskAudit.setAudit(TaskAuditEnum.SHBH.getValue());
                task.setTaskState(TaskStateEnum.BJ.getValue());
            } else {
                throw new BusinessException(ResponseCodeEnum.ERROR, "审核类型错误");
            }
        }
        this.AuditService.updateTaskAudit(taskAudit);
        this.taskMapper.updateByPrimaryKeySelective(task);

    }

    @Override
    @Transactional
    public MyTask neckTask(Integer taskID, Integer type, User loginUser) {
        Task task = this.taskMapper.selectByPrimaryKey(taskID);
        log.info("任务价格----------------------{}",task.getPrice());
        BigDecimal oldPrice = task.getPrice();
        if (BeanUtil.isEmpty(task)) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "当前任务不存在");
        }
        if (task.getNumber() <= 0) {
            Task updateInstance = this.getUpdateInstance(Task.class);
            updateInstance.setTaskID(task.getTaskID());
            updateInstance.setTaskState(3);
            this.taskMapper.updateByPrimaryKeySelective(updateInstance);
            throw new BusinessException(ResponseCodeEnum.ERROR, "当前任务剩余数量不足，领取失败");
        }
        User user = this.userMapper.selectByPrimaryKey(loginUser.getUserID());
        MyTask userParam = new MyTask();
        userParam.setUserID(user.getUserID());
        userParam.setTaskID(taskID);
        if (type.equals(1)) {
            userParam.setStatus(1);
            MyTask myTask = this.myTaskMapper.selectOne(userParam);
            if (BeanUtil.isNotEmpty(myTask)) {
                if (myTask.getCTime().compareTo(LocalDateTime.now()) > 0) {
                    throw new BusinessException(ResponseCodeEnum.ERROR, "该任务你已经领取，不能重复领取");
                }
            }
        }
        userParam.setState(MyTaskStateEnum.JXZ.getValue());
        userParam.setCTime(LocalDateTime.now().plusHours(task.getSubmitTime()));
        userParam.setPrice(oldPrice);
        //获取用户实得价格
        BigDecimal actualPrice = new BigDecimal(0);
        if (user.getPosition().equals(UserPositionEnum.FWS.getValue()) || user.getPosition().equals(UserPositionEnum.GR.getValue())){
            actualPrice = task.getPrice();
        }else{
            TaskPrice taskPrice = new TaskPrice();
            if (user.getService() != 0){
                taskPrice = this.taskPriceMapper.selectByUser(user.getService(),task.getTaskID());
            }else {
                taskPrice = this.taskPriceMapper.selectByUser(user.getPerson(),task.getTaskID());
            }
            ConfigBrokerage configBrokerage = new ConfigBrokerage();
            if (user.getPerson().equals(0)){
                configBrokerage = this.configBrokerageMapper.queryServiceProviderConfig(user.getService());
            }else {
                configBrokerage = this.configBrokerageMapper.queryServiceProviderConfig(user.getPerson());
            }
            if (UserPositionEnum.PT.getValue().equals(user.getPosition())) {
                if (BeanUtil.isEmpty(taskPrice)){
                    double div = NumberUtil.div(configBrokerage.getDefaultUserProportion().intValue(), 100, 2);
                    if (div > 0) {
                        BigDecimal mul = task.getPrice().multiply(new BigDecimal(div)).setScale(1,BigDecimal.ROUND_HALF_UP);
                        if (mul.compareTo(BigDecimal.ZERO) > 0) {
                            actualPrice = mul;
                        }
                    }
                }else {
                    actualPrice = taskPrice.getUserPrice();
                }
            } else if (UserPositionEnum.TDZ.getValue().equals(user.getPosition())){
                if (BeanUtil.isEmpty(taskPrice)){
                    double div = NumberUtil.div(configBrokerage.getDefaultCaptainProportion().intValue(), 100, 2);
                    if (div > 0) {
                        BigDecimal mul = task.getPrice().multiply(new BigDecimal(div)).setScale(1,BigDecimal.ROUND_HALF_UP);
                        if (mul.compareTo(BigDecimal.ZERO) > 0) {
                            actualPrice = mul;
                        }
                    }
                }else {
                    actualPrice = taskPrice.getTemPrice();
                }
            }else if (UserPositionEnum.ZS.getValue().equals(user.getPosition())){
                task.setPriceType(1);
                actualPrice = new BigDecimal(1);
            }else {
                actualPrice = new BigDecimal(0);
            }
        }
        userParam.setActualPrice(actualPrice);
        userParam.setState(1);
        if (type.equals(1)) {
            userParam.setStatus(MyTaskAuditLogStateEnum.DTJ.getValue());
        } else {
            userParam.setStatus(MyTaskAuditLogStateEnum.SHZ.getValue());
        }
        this.setCreateBaseData(userParam, user);
        this.myTaskMapper.insertSelective(userParam);

        //新增领取审核记录表
        MyTaskAuditLog myTaskAuditLog = new MyTaskAuditLog();
        myTaskAuditLog.setMyTaskID(userParam.getMyTaskID());
        myTaskAuditLog.setState(MyTaskAuditLogStateEnum.DTJ.getValue());
        this.setCreateBaseData(myTaskAuditLog, user);
        int i = this.myTaskAuditLogMapper.insertSelective(myTaskAuditLog);
        if (i == 0) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "新增审核记录表失败");

        }
        return userParam;
    }

    @Override
    public TaskVo statistics(ConfigTaskType configTaskType, User loginUser) {
        Integer configTaskTypeID = configTaskType.getConfigTaskTypeID();
        List<Task> select = null;
        if (configTaskTypeID.equals(0)) {
            Task task = new Task();
            task.setDeleted(0);
            task.setTaskState(1);
            task.setState(TaskStateEnum.JXZ.getValue());
            select = this.taskMapper.select(task);
        } else {
            Task task = new Task();
            task.setDeleted(0);
            task.setTaskState(1);
            task.setConfigTaskTypeID(configTaskTypeID);
            if (configTaskType.getZqType() != null){
                task.setZqType(configTaskType.getZqType());
            }
            task.setState(TaskStateEnum.JXZ.getValue());
            task.setIsScreen(0);
            select = this.taskMapper.select(task);
        }
        User user = this.userMapper.selectByPrimaryKey(loginUser.getUserID());
        for (Task task1 : select) {
            this.checkPriceByUser(task1, user);
        }
        TaskVo taskVo = new TaskVo();
        int totalTime = select.stream().mapToInt(Task::getExpectTime).sum();
        BigDecimal totalPrice = select.stream().map(vo -> ObjectUtils.isEmpty(vo.getPrice()) ? new BigDecimal(0) : vo.getPrice())
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        long total = select.stream().count();
        taskVo.setTotal(total);
        taskVo.setTotalTime(totalTime);
        taskVo.setTotalPrice(totalPrice);
        return taskVo;
    }

    @Override
    public List<Task> selectByName(TaskPackageBo bo) {
        TaskPackage taskPackage = this.taskPackageMapper.selectByPrimaryKey(bo.getTaskPackageID());
        if (BeanUtil.isEmpty(taskPackage)) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "任务包信息不存在");
        }
        List<Task> tasks = this.taskMapper.selectByName(bo.getTaskPackageID(), bo.getTaskName());
        return tasks;
    }

    @Override
    public int removePackage(RemovePackageBo bo, SysAdmin admin) {
        TaskPackage taskPackage = this.taskPackageMapper.selectByPrimaryKey(bo.getTaskPackageID());
        if (BeanUtil.isEmpty(taskPackage)) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "任务包信息不存在");
        }

        Task task = this.taskMapper.selectByPrimaryKey(bo.getTaskID());
        if (BeanUtil.isEmpty(task)) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "任务信息不存在");
        }
        task.setTaskPackageID(0);
        this.setUpdateBaseData(task, admin);
        int i = this.taskMapper.updateByPrimaryKeySelective(task);
        if (i == 0) {
            return 0;
        }
        return 1;
    }

    @Override
    public PageInfo<Task> selectAllList(PageParam pageParam, SysAdmin admin) {
        log.info("【入参】：{}",pageParam);
        SysAdmin sysAdmin = this.sysAdminMapper.selectByPrimaryKey(admin.getSysAdminID());
        List<Task> list = null;
        if (sysAdmin.getUserType().equals("00")){
            PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
            pageParam.getKv().put("deleted", 0);
            list = this.taskMapper.selectAllList(pageParam.getKv());
        }else {
            User user = new User();
            user.setDeleted(0);
            user.setPhone(sysAdmin.getPhonenumber());
            User param = this.userMapper.selectOne(user);
            PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
            pageParam.getKv().put("deleted", 0);
            pageParam.getKv().put("userID", param.getUserID());
            list = this.taskMapper.selectAllList1(pageParam.getKv());
        }

        for (Task task : list) {
            ConfigTaskType configTaskType = this.configTaskTypeMapper.selectByPrimaryKey(task.getConfigTaskTypeID());
            task.setConfigTaskType(configTaskType);
            TaskPackage taskPackage = this.taskPackageMapper.selectByPrimaryKey(task.getTaskPackageID());
            task.setTaskPackage(taskPackage);
            //步骤数据
            TaskStep taskStep = new TaskStep();
            taskStep.setTaskID(task.getTaskID());
            List<TaskStep> select = this.taskStepMapper.select(taskStep);
            task.setTaskStepList(select);
            //提示信息
            TaskPrompt taskPrompt = new TaskPrompt();
            taskPrompt.setTaskID(task.getTaskID());
            List<TaskPrompt> select1 = this.taskPromptMapper.select(taskPrompt);
            task.setTaskPrompts(select1);
            //审核表数据
            TaskAudit taskAudit = new TaskAudit();
            taskAudit.setTaskID(task.getTaskID());
            taskAudit.setAudit(0);
            TaskAudit taskAudit1 = this.auditMapper.selectOne(taskAudit);
            task.setTaskAudit(taskAudit1);
        }
        return new PageInfo<>(list);
    }

    @Override
    @Transactional
    public int addTask(MgtTaskAddBo bo, SysAdmin loginAdmin) {
        log.info("任务新增请求参数：{}", bo);
        Task param = new Task();
        param.setDeleted(0);
        param.setProductName(bo.getProductName());
        List<Task> select = this.taskMapper.select(param);
        if (!CollectionUtils.isEmpty(select)){
            throw new BusinessException(ResponseCodeEnum.ERROR, "任务名重复，请修改后提交");
        }
        Task task = BeanUtil.copyProperties(bo, Task.class);
        task.setTaskState(TaskStateEnum.JXZ.getValue());
        task.setState(StateEnum.PT.getValue());
        task.setResidueNumber(task.getNumber());
        task.setTaskPackageID(0);
        task.setUserID(loginAdmin.getSysAdminID());
        task.setIsScreen(0);
        this.setCreateBaseData(task, loginAdmin);
        int i = this.taskMapper.insertSelective(task);
        if (i == 0) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "新增任务失败");
        }
        List<TaskStep> taskSteps1 = new ArrayList<>();
        //新增步骤表
        for (TaskStep taskSteps : bo.getTaskStepList()) {
            TaskStep taskStep = new TaskStep();
            taskStep.setStepName(taskSteps.getStepName());
            taskStep.setExplain(taskSteps.getExplain());
            taskStep.setPicture(taskSteps.getPicture());
            taskStep.setTaskID(task.getTaskID());
            taskStep.setType(taskSteps.getType());
            this.setCreateBaseData(taskStep, loginAdmin);
            taskSteps1.add(taskStep);
        }
        int i1 = this.taskStepMapper.insertList(taskSteps1);
        if (i1 == 0) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "新增任务步骤失败");
        }
        //新增平台任务提示信息表
        List<TaskPrompt> taskPrompts = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(bo.getTaskPrompts())) {
            for (TaskPrompt taskPrompt : bo.getTaskPrompts()) {
                TaskPrompt taskPrompt1 = new TaskPrompt();
                taskPrompt1.setTaskID(task.getTaskID());
                taskPrompt1.setToast(taskPrompt.getToast());
                this.setCreateBaseData(taskPrompt1, loginAdmin);
                taskPrompts.add(taskPrompt1);
            }
            int i2 = this.taskPromptMapper.insertList(taskPrompts);
            if (i2 == 0) {
                throw new BusinessException(ResponseCodeEnum.ERROR, "新增任务提示信息表数据失败");
            }
        }
        return 1;
    }

    @Override
    @Transactional
    public int uptTask(MgtTaskAddBo bo, SysAdmin loginAdmin) {
        log.info("修改数据入参：{}", bo);
        Task task1 = this.taskMapper.selectByPrimaryKey(bo.getTaskID());
        if (BeanUtil.isEmpty(task1)) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "当前任务不存在");
        }
        Task task = BeanUtil.copyProperties(bo, Task.class);
        this.setUpdateBaseData(task, loginAdmin);
        int i = this.taskMapper.updateByPrimaryKeySelective(task);
        if (i == 0) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "修改任务失败");
        }
        //删除步骤表数据
        TaskStep taskStep = new TaskStep();
        taskStep.setTaskID(task1.getTaskID());
        List<TaskStep> select = this.taskStepMapper.select(taskStep);
        for (TaskStep step : select) {
            this.taskStepMapper.deleteByPrimaryKey(step.getTaskStepID());
        }

        //新增步骤表
        List<TaskStep> taskSteps2 = new ArrayList<>();
        for (TaskStep taskSteps : bo.getTaskStepList()) {
            TaskStep taskStep1 = new TaskStep();
            taskStep1.setStepName(taskSteps.getStepName());
            taskStep1.setExplain(taskSteps.getExplain());
            taskStep1.setPicture(taskSteps.getPicture());
            taskStep1.setType(taskSteps.getType());
            taskStep1.setTaskID(task.getTaskID());
            this.setCreateBaseData(taskStep1, loginAdmin);
            taskSteps2.add(taskStep1);
        }
        int i1 = this.taskStepMapper.insertList(taskSteps2);
        if (i1 == 0) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "新增任务步骤失败");
        }
        //删除之前的任务信息表数据
        TaskPrompt taskPrompt = new TaskPrompt();
        taskPrompt.setTaskID(bo.getTaskID());
        List<TaskPrompt> select1 = this.taskPromptMapper.select(taskPrompt);
        if (CollectionUtil.isNotEmpty(select1)){
            for (TaskPrompt prompt : select1) {
                this.taskPromptMapper.deleteByPrimaryKey(prompt.getTaskPromptID());
            }
        }
        //新增平台任务提示信息表
        ArrayList<TaskPrompt> taskPrompts = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(bo.getTaskPrompts())){
            for (TaskPrompt taskPrompt2 : bo.getTaskPrompts()) {
                TaskPrompt taskPrompt1 = new TaskPrompt();
                taskPrompt1.setTaskID(task.getTaskID());
                taskPrompt1.setToast(taskPrompt2.getToast());
                this.setCreateBaseData(taskPrompt1, loginAdmin);
                taskPrompts.add(taskPrompt1);
            }
            int i2 = this.taskPromptMapper.insertList(taskPrompts);
            if (i2 == 0) {
                throw new BusinessException(ResponseCodeEnum.ERROR, "新增任务提示信息表数据失败");
            }
        }
        return 1;
    }

    @Override
    public PageInfo<Task> releaseList(PageParam pageParam, User user) {
        PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
        pageParam.getKv().put("deleted", 0);
        pageParam.getKv().put("userID", user.getUserID());
        List<Task> tasks = this.taskMapper.releaseList(pageParam.getKv());
        for (Task task : tasks) {
            User user1 = this.userMapper.selectByPrimaryKey(task.getUserID());
            task.setUser(user1);

        }
        return new PageInfo<>(tasks);
    }

    @Override
    public Task publishingDetail(Integer taskID) {
        Task task = this.taskMapper.selectByPrimaryKey(taskID);
        List<MyTaskVo> myTaskVos = this.myTaskMapper.selectByTaskID(taskID);
        task.setMyTaskVos(myTaskVos);
        List<TaskStep> taskSteps = this.taskStepMapper.selectByTaskID(task.getTaskID());
        task.setTaskStepList(taskSteps);
        return task;
    }

    @Override
    public PageInfo<MyTask> getMyTask(PageParam pageParam) {
        PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
        pageParam.getKv().put("deleted", 0);
        List<MyTask> myTasks = this.myTaskMapper.getMyTask(pageParam.getKv());
        for (MyTask p : myTasks) {
            User user = this.userMapper.selectByPrimaryKey(p.getUserID());
            p.setUser(user);
            Task task = this.taskMapper.selectByPrimaryKey(p.getTaskID());
            p.setTask(task);
            //任务步骤信息
            TaskStep taskStep = new TaskStep();
            taskStep.setTaskID(task.getTaskID());
            List<TaskStep> select = this.taskStepMapper.select(taskStep);
            p.setTaskSteps(select);
            //更加领取ID查询领取审核数据
            MyTaskAudit myTaskAudit = new MyTaskAudit();
            myTaskAudit.setMyTaskID(p.getMyTaskID());
            MyTaskAudit myTaskAudit1 = this.taskAuditMapper.selectOne(myTaskAudit);
            p.setMyTaskAudit(myTaskAudit1);
        }
        return new PageInfo<>(myTasks);
    }

    @Override
    public PageInfo<Task> getList(PageParam pageParam, User loginUser) {
        PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
        pageParam.getKv().put("deleted", 0);
        pageParam.getKv().put("userID", loginUser.getUserID());
        List<Task> tasks = this.taskMapper.getList(pageParam.getKv());
        for (Task task : tasks) {
            ConfigTaskType configTaskType = this.configTaskTypeMapper.selectByPrimaryKey(task.getConfigTaskTypeID());
            task.setConfigTaskType(configTaskType);
        }
        return new PageInfo<>(tasks);
    }

    @Override
    public int shield(Integer[] taskIDs, User loginUser) {
        for (Integer taskID : taskIDs) {
            Task task = this.taskMapper.selectByPrimaryKey(taskID);
            if (BeanUtil.isEmpty(task)) {
                throw new BusinessException(ResponseCodeEnum.ERROR, "任务不存在");
            }
            if (task.getIsScreen().equals(OnTypeEnum.OFF.getValue())) {
                task.setIsScreen(OnTypeEnum.ON.getValue());
            } else {
                task.setIsScreen(OnTypeEnum.OFF.getValue());
            }
            this.setUpdateBaseData(task, loginUser);
            int i = this.taskMapper.updateByPrimaryKeySelective(task);
            if (i == 0) {
                throw new BusinessException(ResponseCodeEnum.ERROR, "修改失败");
            }
        }
        return 1;
    }

    @Override
    public int addTaskPackage(AddTaskPackageBo bo, SysAdmin admin) {
        Task task = this.taskMapper.selectByPrimaryKey(bo.getTaskID());
        if (BeanUtil.isEmpty(task)) {
            throw new BusinessException("当前任务不存在");
        }
        TaskPackage taskPackage = this.taskPackageMapper.selectByPrimaryKey(bo.getTaskPackageID());
        if (BeanUtil.isEmpty(taskPackage)) {
            throw new BusinessException("当前任务包不存在");
        }
        task.setTaskPackageID(bo.getTaskPackageID());
        this.setUpdateBaseData(task, admin);
        int i = this.taskMapper.updateByPrimaryKeySelective(task);
        if (i == 0) {
            throw new BusinessException("添加进任务包失败");
        }
        return 1;
    }

    @Override
    public PageInfo<MyTask> getPromotionList(PageParam pageParam, User loginUser) {
        PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
        pageParam.getKv().put("deleted", 0);
        pageParam.getKv().put("userID", loginUser.getUserID());
        List<MyTask> tasks = this.taskMapper.getPromotionList(pageParam.getKv());
        for (MyTask task : tasks) {
            User user = this.userMapper.selectByPrimaryKey(task.getUserID());
            task.setUser(user);
            Task task1 = this.taskMapper.selectByPrimaryKey(task.getTaskID());
            task.setTask(task1);
        }
        return new PageInfo<>(tasks);
    }

    @Override
    public Task uptPrice(UptPriceBo bo, User loginUser) {
        log.info("入参：{}", bo);
        //根据任务ID查询当前任务
        Task task = this.taskMapper.selectByPrimaryKey(bo.getTaskID());
        if (BeanUtil.isEmpty(task)) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "当前任务不存在");
        }
        if (!task.getTaskState().equals(TaskStateEnum.WCG.getValue()) &&
                !task.getTaskState().equals(TaskStateEnum.YZT.getValue())) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "只有任务是已暂停或未成功状态才能进行修改");
        }
        if (task.getPrice().compareTo(bo.getPrice()) > 0) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "当前修改的价格小于任务价格");
        }
        //新增修改审核
        TaskAudit taskAudit = new TaskAudit();
        taskAudit.setUserID(loginUser.getUserID());
        taskAudit.setTaskID(bo.getTaskID());
        taskAudit.setAuditType(TaskAuditTypeEnum.XGJG.getValue());
        taskAudit.setPrice(task.getPrice());
        taskAudit.setUptPrice(bo.getPrice());
        taskAudit.setPriceDifference(bo.getPriceDifference());
        taskAudit.setState(task.getTaskState());
        this.setCreateBaseData(taskAudit, loginUser);
        int i = this.auditMapper.insertSelective(taskAudit);
        if (i == 0) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "新增修改价格审核表失败");
        }
        task.setPrice(bo.getPrice());
        task.setTaskState(TaskStateEnum.DSH.getValue());
        task.setPayMent(bo.getPriceDifference());
        task.setUptState(taskAudit.getState());
        task.setOrderType(TaskAuditTypeEnum.XGJG.getValue());
        this.taskMapper.updateByPrimaryKeySelective(task);
        //增加操作记录表数据
        ConfigRecord configRecord = new ConfigRecord(
                loginUser.getUserID(),
                ConfigRecordTypeEnum.JG.getValue(),
                bo.getTaskID(),
                "对任务ID：" + bo.getTaskID() + "进行了修改价格"
        );
        this.setCreateBaseData(configRecord, loginUser);
        int i2 = this.configRecordMapper.insertSelective(configRecord);
        if (i2 == 0) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "新增操作记录表数据失败");
        }
        return task;
    }

    @Override
    public Task uptNumber(UptNumberBo bo, User loginUser) {
        //根据任务ID查询当前任务
        Task task = this.taskMapper.selectByPrimaryKey(bo.getTaskID());
        if (BeanUtil.isEmpty(task)) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "当前任务不存在");
        }
        if (!task.getTaskState().equals(TaskStateEnum.WCG.getValue()) &&
                !task.getTaskState().equals(TaskStateEnum.YZT.getValue())) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "只有任务是已暂停或未成功状态才能进行修改");
        }
        //新增修改审核
        TaskAudit taskAudit = new TaskAudit();
        taskAudit.setUserID(loginUser.getUserID());
        taskAudit.setTaskID(bo.getTaskID());
        taskAudit.setAuditType(TaskAuditTypeEnum.XGSL.getValue());
        taskAudit.setNumber(task.getResidueNumber());
        taskAudit.setUptNumber(bo.getNumber());
        taskAudit.setPriceDifference(bo.getPriceDifference());
        taskAudit.setState(task.getTaskState());
        if (bo.getType().equals(OrderTypeEnum.GM.getValue())) {
            taskAudit.setType(OrderTypeEnum.GM.getValue());
            task.setResidueNumber(task.getResidueNumber() + bo.getNumber());
            task.setPayMent(bo.getPriceDifference());
        } else {
            if (task.getResidueNumber() - (bo.getNumber()) < 0) {
                throw new BusinessException(ResponseCodeEnum.ERROR, "当前减少的数量大于当前任务剩余数量");
            }
            taskAudit.setType(OrderTypeEnum.FB.getValue());
            task.setResidueNumber(task.getResidueNumber() - bo.getNumber());
        }
        this.setCreateBaseData(taskAudit, loginUser);
        int i = this.auditMapper.insertSelective(taskAudit);
        if (i == 0) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "新增修改数量审核表失败");
        }
        task.setTaskState(TaskStateEnum.DSH.getValue());
        task.setUptState(taskAudit.getState());
        task.setOrderType(TaskAuditTypeEnum.XGSL.getValue());
        this.taskMapper.updateByPrimaryKeySelective(task);
        //增加操作记录表数据
        ConfigRecord configRecord = new ConfigRecord(
                loginUser.getUserID(),
                ConfigRecordTypeEnum.SL.getValue(),
                bo.getTaskID(),
                "对任务ID：" + bo.getTaskID() + "进行了修改数量"
        );
        this.setCreateBaseData(configRecord, loginUser);
        int i2 = this.configRecordMapper.insertSelective(configRecord);
        if (i2 == 0) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "新增操作记录表数据失败");
        }
        return task;
    }

    @Override
    @Transactional
    public TaskOrder taskOrder(Task pageParam, HttpServletRequest request, User loginUser) {
        log.info("下单参数：{}", pageParam);
        Task task = this.taskMapper.selectByPrimaryKey(pageParam.getTaskID());
        if (BeanUtil.isEmpty(task)) {
            throw new BusinessException(ResponseCodeEnum.NULL_VALUE, "没有获取到任务信息");
        }
        User user = this.userMapper.selectByPrimaryKey(loginUser.getUserID());
        this.checkLogicExist(user, "没有获取到下单用户信息");

        //订单编号
        String orderCode = OrderTypeEnum.FB.getMarker() + loginUser.getPhone() + System.currentTimeMillis();
        //新增任务订单
        TaskOrder taskOrder = new TaskOrder();
        taskOrder.setUserID(loginUser.getUserID());
        taskOrder.setTaskNum(task.getNumber());
        taskOrder.setTaskPrice(task.getPrice());
        taskOrder.setPrice(task.getPayMent());
        taskOrder.setOrderState(TaskOrderStateEnum.DZF.getValue());
        taskOrder.setPayType(1);
        taskOrder.setPayTime(LocalDateTime.now());
        taskOrder.setPayExpireTime(LocalDateTime.now().plusMinutes(5L));
        taskOrder.setTaskID(task.getTaskID());
        taskOrder.setOrderCode(orderCode);
        Integer businessType = 0;
        String bodyInfo = "";
        if (task.getOrderType().equals(TaskOrderTypeEnum.FBRW.getValue())) {
            taskOrder.setOrderType(TaskOrderTypeEnum.FBRW.getValue());
            businessType = PayOrderBusinessTypeEnum.RWFB.getValue();
            bodyInfo = "任务发布下单";
        } else if (task.getOrderType().equals(TaskOrderTypeEnum.XGDJ.getValue())) {
            taskOrder.setOrderType(TaskOrderTypeEnum.XGDJ.getValue());
            businessType = PayOrderBusinessTypeEnum.XGJG.getValue();
            bodyInfo = "修改任务价格下单";
        } else {
            taskOrder.setOrderType(TaskOrderTypeEnum.ZJSL.getValue());
            businessType = PayOrderBusinessTypeEnum.XGSL.getValue();
            bodyInfo = "增加任务数量下单";
        }

        this.setCreateBaseData(taskOrder, loginUser);
        int i = this.taskOrderMapper.insertSelective(taskOrder);
        if (i == 0) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "新增任务订单失败");
        }
        Integer channelId = 0;
        if (pageParam.getPhoneSystems().equals(1)) {
            channelId = PayChannelEnum.ALIPAY_APP_ANDROID.getChannelId();
        } else if (pageParam.getPhoneSystems().equals(2)) {
            channelId = PayChannelEnum.ALIPAY_WAP.getChannelId();
        } else {
            throw new BusinessException(ResponseCodeEnum.ERROR, "请传递正确的支付渠道码");
        }
        //去下单
        PayOrder payOrder = new PayOrder(
                channelId,
                orderCode,
                "任务订单",
                bodyInfo,
                IPUtil.getIPAddress(request),
                loginUser.getUserID(),
                PayOrderTypeEnum.RW.getValue(),
                taskOrder.getTaskOrderID(),
                taskOrder.getPrice(),
                businessType,
                new BigDecimal(0),
                LocalDateTime.now().plusMinutes(5L)
        );
        User user1 = this.userMapper.selectByPrimaryKey(loginUser.getUserID());
        PayOrder pay = this.payOrderService.pay(payOrder, user1);
        String payReqRespInfo = pay.getPayReqResp();
        taskOrder.setPayReqRespInfo(payReqRespInfo);
        if (pay.getExpireTime() != null) {
            long l = DateUtils.durationToMillis(LocalDateTime.now(), pay.getExpireTime());
            //加入延时队列
            TaskBase base = new TaskBase(taskOrder.getServiceID(), 1, taskOrder.getServiceID());
            //获取相差时间
            DelayTask task1 = new DelayTask(base, l);
            this.delayQueueManager.put(task1);
            log.info("订单：{}加入延时队列,过期时间{}", taskOrder.getServiceID(), pay.getExpireTime());
        }
        return taskOrder;
    }

    @Override
    public void payNotify(PayOrder payOrder) {
        //获取任务订单
        TaskOrder taskOrder = this.taskOrderMapper.selectByPrimaryKey(payOrder.getRelatedOrderID());
        if (BeanUtil.isEmpty(taskOrder)) {
            throw new BusinessException(ResponseCodeEnum.NULL_VALUE, "没有获取到任务订单");
        }
        //获取当前任务信息
        Task task = this.taskMapper.selectByPrimaryKey(taskOrder.getTaskID());
        if (BeanUtil.isEmpty(task)) {
            throw new BusinessException(ResponseCodeEnum.NULL_VALUE, "没有获取到任务信息");
        }
        TaskOrder updateOrder = this.getUpdateInstance(TaskOrder.class);
        updateOrder.setTaskOrderID(taskOrder.getTaskOrderID());
        //判断支付是否成功
        if (PayOrderStatusEnum.NOTIFY_SUCCESS.getValue().equals(payOrder.getStatus())) {
            updateOrder.setOrderState(TaskOrderStateEnum.ZFCG.getValue());
            updateOrder.setFinishTime(LocalDateTime.now());
            updateOrder.setTotalPrice(payOrder.getNotifyPayerAmount());
            if (task.getOrderType().equals(TaskOrderTypeEnum.FBRW.getValue())) {
                task.setActualPrice(task.getActualPrice().add(payOrder.getNotifyPayerAmount()));
                task.setTaskState(TaskStateEnum.JXZ.getValue());
                task.setResidueAmount(payOrder.getNotifyAmount());
            } else if (task.getOrderType().equals(TaskOrderTypeEnum.XGDJ.getValue()) ||
                    task.getOrderType().equals(TaskOrderTypeEnum.ZJSL.getValue())) {
                task.setActualPrice(task.getActualPrice().add(payOrder.getNotifyPayerAmount()));
                task.setTaskState(task.getUptState());
                task.setResidueAmount(task.getResidueAmount().add(payOrder.getNotifyAmount()));
            }
        } else {
            updateOrder.setOrderState(TaskOrderStateEnum.ZFSB.getValue());
        }
        this.taskOrderMapper.updateByPrimaryKeySelective(updateOrder);
        this.taskMapper.updateByPrimaryKeySelective(task);
        //删除队列信息
        this.delayQueueManager.remove(taskOrder.getServiceID());
    }

    @Override
    public TaskTotalVo tgTotal(User loginUser) {
        TaskTotalVo taskTotalVo = this.taskMapper.tgTotal(loginUser.getUserID());
        int size = this.taskMapper.getMyTaskList(loginUser.getUserID());
        if (loginUser.getUserID().equals(6)){
            taskTotalVo.setNum(52471 + size);
        } else {
            taskTotalVo.setNum(size);
        }
        return taskTotalVo;
    }

    @Override
    public void checkExpire(String serviceID) {
        Task task = this.selectTaskByServiceID(serviceID);
        if (BeanUtil.isEmpty(task)) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "找不到该任务");
        }
        User user = this.userMapper.selectByPrimaryKey(task.getUserID());
        //判断该项目是否已完成
        if (!task.getTaskState().equals(TaskStateEnum.YCG.getValue())) {
            //未完成的校验日期是否过期
            if (LocalDateTime.now().isAfter(task.getEndTime())
                    || LocalDateTime.now().equals(task.getEndTime())) {
                //已过期
                log.info("任务{}已到结束时间处理", task.getServiceID());
                //如果是平台任务，直接修改状态为已完成
                if (task.getState().equals(TaskStateEnum.JXZ.getValue())) {
                    task.setTaskState(TaskStateEnum.YCG.getValue());
                } else {
                    //如果是悬赏任务，将任务剩余的
                    task.setTaskState(TaskStateEnum.YCG.getValue());
                    //根据任务ID查询订单信息
                    TaskOrder taskOrder = new TaskOrder();
                    taskOrder.setTaskID(task.getTaskID());
                    taskOrder.setDeleted(0);
                    List<TaskOrder> select = this.taskOrderMapper.select(taskOrder);
                    BigDecimal residueAmount = task.getResidueAmount();
                    // 订单退款
                    for (TaskOrder order : select) {
                        if (order.getPrice().compareTo(residueAmount) == -1) {
                            this.payOrderService.payRefund(order.getOrderCode(),
                                    order.getPrice(), "任务到结束时间退款",
                                    PayProperties.payReturnUrl, user);
                            residueAmount = residueAmount.subtract(order.getPrice());
                        } else {
                            this.payOrderService.payRefund(order.getOrderCode(),
                                    residueAmount, "任务到结束时间退款", PayProperties.payReturnUrl, user);
                        }
                    }
                }
            }
        }

        int i = this.taskMapper.updateByPrimaryKeySelective(task);
        if (i == 0) {
            throw new BusinessException(ResponseCodeEnum.ERROR, "任务到期，状态修改失败");
        }

    }

    @Override
    public PageInfo<Task> taskListAll(PageParam pageParam) {
        log.info("入参：{}", pageParam);
        PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
        pageParam.getKv().put("deleted", 0);
        Integer orderField = (Integer) pageParam.getKv().get("sort");
        if (orderField.equals(SortEnum.ZX.getValue())) {
            pageParam.getKv().put("orderField", "submitTime");
            pageParam.getKv().put("orderType", "desc");
        } else if (orderField.equals(SortEnum.ZR.getValue())) {
            pageParam.getKv().put("orderField", "residueNumber");
            pageParam.getKv().put("orderType", "asc");
        } else if (orderField.equals(SortEnum.GYJ.getValue())) {
            pageParam.getKv().put("orderField", "price");
            pageParam.getKv().put("orderType", "desc");
        } else if (orderField.equals(SortEnum.YSS.getValue())) {
            pageParam.getKv().put("orderField", "expectTime");
            pageParam.getKv().put("orderType", "asc");
        } else {
            pageParam.getKv().put("orderField", "createTime");
            pageParam.getKv().put("orderType", "desc");
        }
        List<Task> tasks = this.taskMapper.taskListAll(pageParam.getKv());
        for (Task task : tasks) {
            ConfigTaskType configTaskType = this.configTaskTypeMapper.selectByPrimaryKey(task.getConfigTaskTypeID());
            task.setConfigTaskType(configTaskType);
        }
        return new PageInfo<>(tasks);
    }

    @Override
    public TaskVo taskListTotal(Integer state, User loginUser) {
        User user = this.userMapper.selectByPrimaryKey(loginUser.getUserID());
        Task task = new Task();
        task.setState(state);
        task.setTaskState(1);
        task.setDeleted(0);
        task.setIsScreen(0);
        List<Task> select = this.taskMapper.select(task);
        for (Task task1 : select) {
            this.checkPriceByUser(task1, user);
        }
        TaskVo taskVo = new TaskVo();
        int totalTime = select.stream().mapToInt(Task::getExpectTime).sum();
        BigDecimal totalPrice = select.stream().map(vo -> ObjectUtils.isEmpty(vo.getPrice()) ? new BigDecimal(0) : vo.getPrice())
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        long total = select.stream().count();
        taskVo.setTotal(total);
        taskVo.setTotalTime(totalTime);
        taskVo.setTotalPrice(totalPrice);
        return taskVo;
    }

    @Override
    public void reloadStateQueue() {
        log.info("初始化未完成任务进入延时队列");
        PageParam pageParam = new PageParam();
        pageParam.setPage(1);
        pageParam.setPageSize(1000);
        boolean flag = true;
        while (flag) {
            //获取未完成的数据
            PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
            List<Task> list = this.taskMapper.queryNoPayOrder();
            log.info("未完成的任务：{}", list);
            for (Task task : list) {
                User user = this.userMapper.selectByPrimaryKey(task.getUserID());
                Task updateInstance = this.getUpdateInstance(Task.class);
                updateInstance.setTaskID(task.getTaskID());
                if (LocalDateTime.now().isBefore(task.getEndTime())) {
                    //加入延时队列
                    TaskBase base = new TaskBase(task.getServiceID(), 3, task.getServiceID());
                    long l = DateUtils.durationToMillis(LocalDateTime.now(), task.getEndTime());
                    //获取相差时间
                    DelayTask task1 = new DelayTask(base, l);
                    this.delayQueueManager.put(task1);
                    log.info("任务：{}加入延时队列，延时毫秒{}，过期时间：{}", task.getServiceID(), l, task.getEndTime());
                } else {
                    log.info("任务：{}已过期", task.getServiceID());
                    //已过期
                    if (task.getState().equals(TaskStateEnum.JXZ.getValue())) {
                        updateInstance.setTaskState(TaskStateEnum.YCG.getValue());
                    } else {
                        //如果是悬赏任务且状态是进行中状态的，将任务剩余的金额退款
                        if (task.getTaskState().equals(TaskStateEnum.JXZ.getValue())) {
                            updateInstance.setTaskState(TaskStateEnum.YCG.getValue());
                            //根据任务ID查询订单信息
                            TaskOrder taskOrder = new TaskOrder();
                            taskOrder.setTaskID(task.getTaskID());
                            taskOrder.setDeleted(0);
                            List<TaskOrder> select = this.taskOrderMapper.select(taskOrder);
                            BigDecimal residueAmount = task.getResidueAmount();
                            // 订单退款
                            for (TaskOrder order : select) {
                                try {
                                    if (order.getPrice().compareTo(residueAmount) == -1) {
                                        log.info("悬赏任务过期，开始退款");
                                        this.payOrderService.payRefund(order.getOrderCode(),
                                                order.getPrice(), "任务到结束时间退款", PayProperties.payReturnUrl, user);
                                        residueAmount = residueAmount.subtract(order.getPrice());
                                    } else {
                                        this.payOrderService.payRefund(order.getOrderCode(),
                                                residueAmount, "任务到结束时间退款", PayProperties.payReturnUrl, user);
                                    }
                                } catch (Exception e) {
                                    log.error(e.getMessage(), e);
                                    continue;
                                }

                            }
                        }

                    }
                }
                int i = this.taskMapper.updateByPrimaryKeySelective(updateInstance);
                if (i == 0) {
                    throw new BusinessException(ResponseCodeEnum.ERROR, "修改任务状态为已完成失败");
                }
            }

            //当获取的列表小于分页大小，则没有更多数据，停止轮询
            if (list.size() < pageParam.getPageSize()) {
                flag = false;
            } else {
                pageParam.setPage(pageParam.getPage() + 1);
            }
        }
    }

    @Override
    public GetTaskNumberVo getTaskNumber() {
        int total = this.taskMapper.getNumber();
        int yTotal = this.taskMapper.getYNumber();
        int rTotal = this.taskMapper.getRNumber();
        GetTaskNumberVo getTaskNumberVo = new GetTaskNumberVo();
        getTaskNumberVo.setTotal(total);
        getTaskNumberVo.setRTotal(rTotal);
        getTaskNumberVo.setYTotal(yTotal);
        return getTaskNumberVo;
    }

    @Override
    public List<GetTaskTypeNumberVo> getTaskTypeNumber(SysAdmin admin) {
        SysAdmin sysAdmin = this.sysAdminMapper.selectByPrimaryKey(admin.getSysAdminID());
        List<GetTaskTypeNumberVo> taskTypeNumber = new ArrayList<>();
        if (sysAdmin.getUserType().equals("01")){
            User user = new User();
            user.setPhone(sysAdmin.getPhonenumber());
            user.setDeleted(0);
            User param = this.userMapper.selectByPrimaryKey(user);

        }else {
             taskTypeNumber = this.taskMapper.getTaskTypeNumber();
        }

        return taskTypeNumber;
    }

    @Override
    public List<GetUserVo> getRegisterNumber(String time) {
        String userIDs = "";
        SysAdmin sysAdmin = SecurityUtils.getLoginUser().getSysAdmin();
        sysAdmin = this.sysAdminMapper.selectByPrimaryKey(sysAdmin.getSysAdminID());
        if (sysAdmin.getUserType().equals("01")) {
            User user = new User();
            user.setDeleted(0);
            user.setPhone(sysAdmin.getPhonenumber());
            User param = this.userMapper.selectOne(user);

            UserPromotion userPromotion = new UserPromotion();
            userPromotion.setUserID(param.getUserID());
            userPromotion.setDeleted(0);
            List<UserPromotion> select = this.userPromotionMapper.select(userPromotion);
            //递归查询所有间接用户
            List<Integer> userIDList = new ArrayList<>();
            for (UserPromotion promotion : select) {
                this.userService.queryUserID(userIDList, promotion.getPUser());
            }
            userIDList.add(param.getUserID());
            userIDs = userIDList.stream() .map(Object::toString) .collect(Collectors.joining(","));
        }
        return this.taskMapper.getRegisterNumber(time, userIDs);
    }

    @Override
    public Task selectTaskByTaskIDMgt(Integer taskID, User loginUser) {
        Task task = taskMapper.selectByPrimaryKey(taskID);
        ConfigTaskType configTaskType = this.configTaskTypeMapper.selectByPrimaryKey(task.getConfigTaskTypeID());
        task.setConfigTaskType(configTaskType);
        User user = this.userMapper.selectByPrimaryKey(loginUser.getUserID());
        this.checkPriceByUser(task, user);
        TaskPrompt taskPrompt = new TaskPrompt();
        taskPrompt.setTaskID(taskID);
        List<TaskPrompt> select2 = this.taskPromptMapper.select(taskPrompt);
        task.setTaskPrompts(select2);
        List<TaskStep> select = this.taskStepMapper.selectByTaskID(taskID);
        task.setTaskStepList(select);
        MyTask select1 = this.myTaskMapper.selectMyTask(taskID, loginUser.getUserID());
        if (BeanUtil.isEmpty(select1)) {
            MyTask myTask = new MyTask();
            myTask.setState(0);
            task.setMyTasks(myTask);
        } else {
            task.setMyTasks(select1);
        }
        MyTaskAudit myTaskAudit = new MyTaskAudit();
        myTaskAudit.setTaskID(taskID);
        myTaskAudit.setUserID(loginUser.getUserID());
        MyTaskAudit myTaskAudit1 = this.taskAuditMapper.selectOne(myTaskAudit);
        task.setMyTaskAudit(myTaskAudit1);
        return task;
    }

    @Override
    public PageInfo<MyTaskAudit> getMyTaskAudit(PageParam pageParam, SysAdmin admin) {
        log.info("入参",pageParam);
        pageParam.getKv().put("deleted", 0);
        SysAdmin sysAdmin = this.sysAdminMapper.selectByPrimaryKey(admin.getSysAdminID());
        List<MyTaskAudit> myTaskAudits = null;
        if (sysAdmin.getUserType().equals("01")) {
            User user1 = new User();
            user1.setDeleted(0);
            user1.setPhone(sysAdmin.getPhonenumber());
            User param = this.userMapper.selectOne(user1);
//
//            UserPromotion userPromotion = new UserPromotion();
//            userPromotion.setUserID(param.getUserID());
//            userPromotion.setDeleted(0);
//            List<UserPromotion> select = this.userPromotionMapper.select(userPromotion);
//            //递归查询所有间接用户
//            List<Integer> userIDList = new ArrayList<>();
//            for (UserPromotion promotion : select) {
//                this.userService.queryUserID(userIDList, promotion.getPUser());
//            }
//            userIDList.add(param.getUserID());
//            String userIDs = userIDList.stream() .map(Object::toString) .collect(Collectors.joining(","));
//            pageParam.getKv().put("userIDs", userIDs);
            pageParam.getKv().put("userID", param.getUserID());
            PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
            myTaskAudits = this.taskAuditMapper.getMyTaskAudit1(pageParam.getKv());
        } else {
            PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
            myTaskAudits = this.taskAuditMapper.getMyTaskAudit(pageParam.getKv());

        }
        for (MyTaskAudit myTaskAudit : myTaskAudits) {
            Task task = this.taskMapper.selectByPrimaryKey(myTaskAudit.getTaskID());
            User user = this.userMapper.selectByPrimaryKey(myTaskAudit.getUserID());
            this.checkPriceByUser(task, user);
            myTaskAudit.setTask(task);
            myTaskAudit.setUser(user);

            //任务步骤信息
            TaskStep taskStep = new TaskStep();
            taskStep.setTaskID(myTaskAudit.getTaskID());
            taskStep.setDeleted(0);
            List<TaskStep> select = this.taskStepMapper.select(taskStep);
            myTaskAudit.setTaskStep(select);
            //提示信息
            TaskPrompt taskPrompt = new TaskPrompt();
            taskPrompt.setTaskID(myTaskAudit.getTaskID());
            taskPrompt.setDeleted(0);
            List<TaskPrompt> select1 = this.taskPromptMapper.select(taskPrompt);
            myTaskAudit.setTaskPrompts(select1);

            ConfigTaskType configTaskType = this.configTaskTypeMapper.selectByPrimaryKey(task.getConfigTaskTypeID());
            myTaskAudit.setConfigTaskType(configTaskType);

        }
        return new PageInfo<>(myTaskAudits);
    }

    @Override
    public int check(String productName) {
        Task param = new Task();
        param.setDeleted(0);
        param.setProductName(productName);
        List<Task> select = this.taskMapper.select(param);
        if (!CollectionUtils.isEmpty(select)){
            return 2;
        }
        return 1;
    }

    @Override
    public MyTaskAudit tgDetail(Integer myTaskID) {
        MyTaskAudit param = new MyTaskAudit();
        param.setDeleted(0);
        param.setMyTaskID(myTaskID);
        MyTaskAudit myTaskAudit = this.taskAuditMapper.selectOne(param);
        if (BeanUtil.isNotEmpty(myTaskAudit)){
            //查询任务信息
            Task task = this.taskMapper.selectByPrimaryKey(myTaskAudit.getTaskID());
            myTaskAudit.setTask(task);
            //查询领取信息
            MyTask myTask = this.myTaskMapper.selectByPrimaryKey(myTaskID);
            myTaskAudit.setMyTask(myTask);
            //查询审核信息
            MyTaskAuditLog auditLog = new MyTaskAuditLog();
            auditLog.setMyTaskID(myTaskID);
            auditLog.setDeleted(0);
            List<MyTaskAuditLog> select = this.myTaskAuditLogMapper.select(auditLog);
            myTaskAudit.setMyTaskAuditLogs(select);

            User user = this.userMapper.selectByPrimaryKey(myTask.getUserID());
            myTaskAudit.setUser(user);
            return myTaskAudit;
        }
        return new MyTaskAudit();
    }

    @Override
    public int screen(List<Integer> taskIDs, SysAdmin loginUser) {
        if (CollectionUtils.isEmpty(taskIDs)){
            throw new BusinessException("任务ID必传");
        }
        for (Integer taskID : taskIDs) {
            Task task = this.taskMapper.selectByPrimaryKey(taskID);
            if (BeanUtil.isEmpty(task)){
                throw new BusinessException("任务ID不存在");
            }
            if(task.getIsScreen().equals(OnTypeEnum.ON.getValue())){
                throw new BusinessException("该任务："+task.getProductName()+"已是屏蔽状态");
            }
            Task updateInstance = this.getUpdateInstance(Task.class);
            updateInstance.setTaskID(task.getTaskID());
            updateInstance.setIsScreen(OnTypeEnum.ON.getValue());
            this.setUpdateBaseData(updateInstance,loginUser);
            int i = this.taskMapper.updateByPrimaryKeySelective(updateInstance);
            if (i == 0){
                throw new BusinessException("修改任务："+task.getProductName()+"失败");
            }
        }
        return 1;
    }

    @Override
    public int restore(List<Integer> taskIDs, SysAdmin loginSysAdmin) {
        if (CollectionUtils.isEmpty(taskIDs)){
            throw new BusinessException("任务ID必传");
        }
        for (Integer taskID : taskIDs) {
            Task task = this.taskMapper.selectByPrimaryKey(taskID);
            if (BeanUtil.isEmpty(task)){
                throw new BusinessException("任务ID不存在");
            }
            if(task.getIsScreen().equals(OnTypeEnum.OFF.getValue())){
                throw new BusinessException("该任务："+task.getProductName()+"已是未屏蔽状态");
            }
            Task updateInstance = this.getUpdateInstance(Task.class);
            updateInstance.setTaskID(task.getTaskID());
            updateInstance.setIsScreen(OnTypeEnum.OFF.getValue());
            this.setUpdateBaseData(updateInstance,loginSysAdmin);
            int i = this.taskMapper.updateByPrimaryKeySelective(updateInstance);
            if (i == 0){
                throw new BusinessException("修改任务："+task.getProductName()+"失败");
            }
        }
        return 1;
    }

    @Override
    public int batchTop(TaskTopBo bo, SysAdmin loginSysAdmin) {
        if (CollectionUtils.isEmpty(bo.getTaskIDs())){
            throw new BusinessException("任务ID不能为空，置顶失败");
        }
        for (Integer taskID : bo.getTaskIDs()) {
            Task task = this.taskMapper.selectByPrimaryKey(taskID);
            if (BeanUtil.isEmpty(task)){
                throw new BusinessException("该任务ID："+taskID+"不存在");
            }
            Task updateInstance = this.getUpdateInstance(Task.class);
            updateInstance.setTaskID(taskID);
            updateInstance.setTaskSort(1);
            updateInstance.setUpdateTime(LocalDateTime.now());
            updateInstance.setUpdateBy(loginSysAdmin.getSysAdminID());
            int i = this.taskMapper.updateByPrimaryKeySelective(updateInstance);
            if (i == 0){
                throw new BusinessException("置顶任务："+task.getProductName()+"失败");
            }
        }
        return 1;
    }

    @Override
    public int batchFall(TaskTopBo bo, SysAdmin loginSysAdmin) {
        if (CollectionUtils.isEmpty(bo.getTaskIDs())){
            throw new BusinessException("任务ID不能为空，置顶失败");
        }
        for (Integer taskID : bo.getTaskIDs()) {
            Task task = this.taskMapper.selectByPrimaryKey(taskID);
            if (BeanUtil.isEmpty(task)){
                throw new BusinessException("该任务ID："+taskID+"不存在");
            }
            Task updateInstance = this.getUpdateInstance(Task.class);
            updateInstance.setTaskID(taskID);
            updateInstance.setTaskSort(-1);
            updateInstance.setUpdateTime(LocalDateTime.now());
            updateInstance.setUpdateBy(loginSysAdmin.getSysAdminID());
            int i = this.taskMapper.updateByPrimaryKeySelective(updateInstance);
            if (i == 0){
                throw new BusinessException("降底任务："+task.getProductName()+"失败");
            }
        }
        return 1;
    }

    @Override
    public PageInfo<MyTaskAudit> getMyTaskAuditXS(PageParam pageParam, SysAdmin loginSysAdmin) {
        log.info("入参",pageParam);
        pageParam.getKv().put("deleted", 0);
        SysAdmin sysAdmin = this.sysAdminMapper.selectByPrimaryKey(loginSysAdmin.getSysAdminID());
        List<MyTaskAudit> myTaskAudits = null;
        if (sysAdmin.getUserType().equals("01")) {
            User user1 = new User();
            user1.setDeleted(0);
            user1.setPhone(sysAdmin.getPhonenumber());
            User param = this.userMapper.selectOne(user1);
            pageParam.getKv().put("userID", param.getUserID());
            PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
            myTaskAudits = this.taskAuditMapper.getMyTaskAuditXS1(pageParam.getKv());
        } else {
            PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
            myTaskAudits = this.taskAuditMapper.getMyTaskAuditXS(pageParam.getKv());

        }
        for (MyTaskAudit myTaskAudit : myTaskAudits) {
            Task task = this.taskMapper.selectByPrimaryKey(myTaskAudit.getTaskID());
            User user = this.userMapper.selectByPrimaryKey(myTaskAudit.getUserID());
            this.checkPriceByUser(task, user);
            myTaskAudit.setTask(task);
            myTaskAudit.setUser(user);

            //任务步骤信息
            TaskStep taskStep = new TaskStep();
            taskStep.setTaskID(myTaskAudit.getTaskID());
            taskStep.setDeleted(0);
            List<TaskStep> select = this.taskStepMapper.select(taskStep);
            myTaskAudit.setTaskStep(select);
            //提示信息
            TaskPrompt taskPrompt = new TaskPrompt();
            taskPrompt.setTaskID(myTaskAudit.getTaskID());
            taskPrompt.setDeleted(0);
            List<TaskPrompt> select1 = this.taskPromptMapper.select(taskPrompt);
            myTaskAudit.setTaskPrompts(select1);

            ConfigTaskType configTaskType = this.configTaskTypeMapper.selectByPrimaryKey(task.getConfigTaskTypeID());
            myTaskAudit.setConfigTaskType(configTaskType);

        }
        return new PageInfo<>(myTaskAudits);
    }

    @Override
    public int uptTaskPrice(UptTaskPriceBo bo, User loginUser) {
        User user = this.userMapper.selectByPrimaryKey(loginUser.getUserID());
        if (BeanUtil.isEmpty(user)){
            throw new BusinessException("当前用户信息不存在");
        }
        Task task = this.taskMapper.selectByPrimaryKey(bo.getTaskID());
        if (BeanUtil.isEmpty(task)){
            throw new BusinessException("当前任务信息不存在");
        }
        if (!user.getPosition().equals(UserPositionEnum.FWS.getValue()) &&
                !user.getPosition().equals(UserPositionEnum.TYB.getValue())){
            throw new BusinessException("只有服务商才可以进行任务调价");
        }
        TaskPrice price = new TaskPrice();
        price.setUserID(user.getUserID());
        price.setTaskID(bo.getTaskID());
        price.setDeleted(0);
        TaskPrice taskPrice = this.taskPriceMapper.selectOne(price);
        if (BeanUtil.isEmpty(taskPrice)){
            price.setTemPrice(bo.getTemPrice());
            price.setUserPrice(bo.getUserPrice());
            this.setCreateBaseData(price,loginUser);
            int i = this.taskPriceMapper.insertSelective(price);
            if (i == 0){
                throw new BusinessException("调价失败");
            }
        }else {
            taskPrice.setUserPrice(bo.getUserPrice());
            taskPrice.setTemPrice(bo.getTemPrice());
            this.setUpdateBaseData(taskPrice,loginUser);
            int i = this.taskPriceMapper.updateByPrimaryKeySelective(taskPrice);
            if (i == 0){
                throw new BusinessException("调价失败");
            }
        }
        return 1;
    }
}